【问题标题】:How to loop DOM elements and store as an array?如何循环 DOM 元素并存储为数组?
【发布时间】:2017-07-28 05:18:38
【问题描述】:

我正在通过报废获取数据。 数据源是一个表,我需要获取每个 (tr) 的数据。

该表有 3 (td),即:

  • 标题
  • 日期
  • 链接

这是我使用的代码:

$data = array();
$counter = 1;
$index = 0;

foreach($html->find('#middle table tr td') as $source){

    $dont_include = array(
        '<td>CONTAIN TEXT THAT I DONT WNAT TO INCLUDE IN HERE</td>'
    );

    if (!in_array($source->outertext, $dont_include)) {

        // IF IT CONTAIN LINK THEN GET IT LINK
        // THE SOURCE DATA FOR LINK IS SOMETHING LIKE 
        // <td><a href="">xx</a></td>
        if(strstr($source->innertext, 'http://')){

               $a = new SimpleXMLElement($source->innertext);

               $the_link = (string) $a['href'][0];
               $data[$index] = array('link' => $the_link);;
        }else{
            if ($counter==2) {
                $data[$index] = array('title' => $source->innertext);
            }else{
                $data[$index] = array('date' => $source->innertext);
                $counter = 0;
                $index++;
            }
        }
    }
    $counter++;
}

print_r($data);

问题: 如何使用此结构将这些值存储在数组中:

Array (
    [0] => Array (
        [title] => ""
        [date] => ""
        [link] => ""
    )
    [1] => Array (
        [title] => ""
        [date] => ""
        [link] => ""
    )
    ...
)

更新,这里是源码结构:

    <!-- THIS IS THE SOURCE , AT THE TOP HERE CONTAIN TD THAT I DONT WANT -->
    <td>title</td>
    <td class="ac">date</td>
    <td width="190"><a href="i need this link" target="_blank">filename , i dont need the file name</a>
    </td>
<td>title</td>
    <td class="ac">date</td>
    <td width="190"><a href="i need this link" target="_blank">filename , i dont need the file name</a>
    </td>
<td>title</td>
    <td class="ac">date</td>
    <td width="190"><a href="i need this link" target="_blank">filename , i dont need the file name</a>
    </td>
<td>title</td>
    <td class="ac">date</td>
    <td width="190"><a href="i need this link" target="_blank">filename , i dont need the file name</a>
    </td>

【问题讨论】:

  • title,date,link 你的 td 数据对吗?
  • tr 可能包含tdth
  • 您能否详细描述您的问题..
  • 在我的答案下方查看它会解决您的问题或出现任何错误
  • @taek 你试过我的解决方案了吗?

标签: php arrays web-scraping domdocument


【解决方案1】:

而不是循环通过td 我建议您循环通过tr 以便您可以创建您的数组。试试这个

$rowData = array();

foreach ($html->find('#middle table tr') as $rows) {
    $cellData = array();

    $cellData['title'] = $rows->children(0)->innertext;
    $cellData['date'] = $rows->children(1)->innertext;
    $cellData['link'] = $rows->children(2)->innertext;

    $rowData[] = $cellData;
}
print_r($rowData);

【讨论】:

  • 投反对票的原因是什么?我已经对此进行了测试,并且可以正常工作
  • 也不是我的反对票,我在问题中提供了源数据:)
  • @B.Desai 这就是答案谢谢!
  • @mickmackusa 感谢您的帮助:)
猜你喜欢
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 2017-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多