我试图从一个网页(我不拥有)中获取数据,然后处理该数据。为此,我需要将其分配给数组或将其写入MySQL DB或其他内容。我想要保存第2、4和6列,以便可以使用它们。到目前为止,下面是我的代码,但是我完全不知道如何处理数据。我认为这与爆炸有关,但我没有设法使它起作用:
<?php
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, 'URL');
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
$dom = new DOMDocument;
@$dom->loadHTML( $content );
//get all td
$items = $dom->getElementsByTagName('td');
//display all text
for ($i = 0; $i < $items->length; $i++)
echo $items->item($i)->nodeValue . "<br/>";
//below doesn't work
$cells = explode(" ", $dom->getElementsByTagName('td'));
echo $cells;
?>
$dom->getElementsByTagName('td');
我会返回一个DOMNodeList
数据类型,而不是一个数据类型,array
因此,explode
对此进行一个操作是行不通的。
顺便说一句,当您已经遍历td
的using时,您想通过爆炸来做for
什么?好像是类似的东西。
代码
<?php
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, 'URL');
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
$dom = new DOMDocument;
@$dom->loadHTML( $content );
//get all td
$items = $dom->getElementsByTagName('td');
// save the 2nd, 4th and 6th column values
$columnsToSave = array( 2, 4, 6 );
$outputArray = array();
for ( $i = 0; $i < $items->length; $i++ ) {
$key = $i + 1;
if( in_array( $key, $columnsToSave ) ) {
$outputArray[ $key ] = $items->item($i)->nodeValue . "<br/>";
}
}
print_r( $outputArray );
?>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句