将抓取结果转换为数组

我正在使用简单的 HTML DOM 抓取网站,输出如下所示:


<tr>

    <th>Satuan</th>

    <th>Harga Barang 1</th>

    <th>Harga Barang 2</th>

    <th>Harga Barang 3</th>

    <th>Harga Barang 4</th>

</tr>

<tr>

    <td>0.5</td>

    <td>Rp 388.000</td>

    <td>Rp 342.000</td>

    <td>Rp 456.000</td>

    <td>Rp 377.000</td>

</tr>

<tr>

    <td>1.0</td>

    <td>Rp 725.000</td>

    <td>Rp 676.000</td>

    <td>Rp 855.000</td>

    <td>Rp 684.000</td>

</tr>

这是我的代码:


<?php

include('simple_html_dom.php');

$html = new simple_html_dom();

$html->load_file("mylink.com/blabla");


foreach($html->find('tr') as $e) {

    echo $e;

}

?>

如何将输出转换为数组?


慕雪6442864
浏览 150回答 1
1回答

泛舟湖上清波郎朗

这是片段,$ret&nbsp; &nbsp; &nbsp;= $html->find('tr');$i&nbsp; &nbsp; &nbsp; &nbsp;= true;$headers = [];foreach ($ret as $key => $value) {&nbsp; &nbsp; if ($i) {&nbsp; &nbsp; &nbsp; &nbsp; // fetching headers of first row&nbsp; &nbsp; &nbsp; &nbsp; foreach ($value->find('th') as $cell) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $headers[] = $cell->plaintext;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; $temp = [];&nbsp; &nbsp; &nbsp; &nbsp; // fetching pending values of td&nbsp; &nbsp; &nbsp; &nbsp; foreach ($value->find('td') as $cell) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $temp[] = $cell->plaintext;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // combining headers with values fetched from not first row&nbsp; &nbsp; &nbsp; &nbsp; $result[] = array_combine($headers, $temp);&nbsp; &nbsp; }&nbsp; &nbsp; $i = false;}print_r($result);die;输出Array(&nbsp; &nbsp; [0] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Satuan] => 0.5&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Harga Barang 1] => Rp 388.000&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Harga Barang 2] => Rp 342.000&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Harga Barang 3] => Rp 456.000&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Harga Barang 4] => Rp 377.000&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; [1] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Satuan] => 1.0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Harga Barang 1] => Rp 725.000&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Harga Barang 2] => Rp 676.000&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Harga Barang 3] => Rp 855.000&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Harga Barang 4] => Rp 684.000&nbsp; &nbsp; &nbsp; &nbsp; ))
打开App,查看更多内容
随时随地看视频慕课网APP