我有 html 表,我想从该表创建数组
$html = '<table>
<tr>
<td>satu</td>
<td>dua</td>
</tr>
<tr>
<td>tiga</td>
<td>empat</td>
</tr>
</table>
我的数组必须是这样的
array(
array(
"satu",
"dua",
),
array(
"tiga",
"empat",
)
)
我试过下面的代码,但无法得到我需要的数组
$crawler = new Crawler();
$crawler->addHTMLContent($html);
$row = array();
$tr_elements = $crawler->filterXPath('//table/tr');
foreach ($tr_elements as $tr) {
// ???????
}
最佳答案
$table = $crawler->filter('table')->filter('tr')->each(function ($tr, $i) {
return $tr->filter('td')->each(function ($td, $i) {
return trim($td->text());
});
});
print_r($table);
以上示例将为您提供一个多维数组,其中第一层是表格行“tr”,第二层是表格列“td”。
编辑
如果您有嵌套表格,此代码会将它们很好地展平成一个一维数组。
$html = 'MY HTML HERE';
$crawler = new Crawler($html);
$flat = function(string $selector) use ($crawler) {
$result = [];
$crawler->filter($selector)->each(function ($table, $i) use (&$result) {
$table->filter('tr')->each(function ($tr, $i) use (&$result) {
$tr->filter('td')->each(function ($td, $i) use (&$result) {
$html = trim($td->html());
if (strpos($html, '<table') !== FALSE) return;
$iterator = $td->getIterator()->getArrayCopy()[0];
$address = $iterator->getNodePath();
if (!empty($html)) $result[$address] = $html;
});
});
});
return $result;
};
// The selector gotta point to the most outwards table.
print_r($flat('#Prod fieldset div table'));
关于php - 如何使用 symfony dom 爬虫将 html 表解析为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38065659/