如何使用Symfony Dom搜寻器将HTML表解析为数组 [英] How to parse html table to array with symfony dom crawler

查看:68
本文介绍了如何使用Symfony Dom搜寻器将HTML表解析为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有html表,我想从该表中创建数组

I have html table and I want to make array from that table

$html = '<table>
<tr>
    <td>satu</td>
    <td>dua</td>
</tr>
<tr>
    <td>tiga</td>
    <td>empat</td>
</tr>
</table>

我的数组必须看起来像这样

My array must look like this

array(
   array(
      "satu",
      "dua",
   ),
   array(
     "tiga",
     "empat",
   )
)

我已经尝试了下面的代码,但无法获得所需的数组

I have tried the below code but could not get the array as I need

$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。

The above example will give you a multidimensional array where the first layer are the table lines "tr" and the second layer are the table columns "td".

编辑

如果您嵌套了表格,则此代码会将它们弄平

If you got nested tables, this code will flatten them out nicely into a single dimension array.

$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'));

这篇关于如何使用Symfony Dom搜寻器将HTML表解析为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆