How to parse html table to array with symfony dom

2019-04-08 02:54发布

问题:

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) {
 // ???????
}

回答1:

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

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".



回答2:

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

    $crawler = new Crawler();
    $crawler->addHTMLContent($html);
    $rows = array();
    $tr_elements = $crawler->filterXPath('//table/tr');
    // iterate over filter results
    foreach ($tr_elements as $i => $content) {
        $tds = array();
        // create crawler instance for result
        $crawler = new Crawler($content);
        //iterate again
        foreach ($crawler->filter('td') as $i => $node) {
           // extract the value
            $tds[] = $node->nodeValue;

        }
        $rows[] = $tds;

    }
    var_dump($rows );exit;

will display

array 
  0 => 
    array 
      0 => string 'satu' 
      1 => string 'dua' 
  1 => 
    array (size=2)
      0 => string 'tiga' 
      1 => string 'empat'