Xpath返回空白页面不';t呼应这些值


Xpath returns blank page doesn't echo the values

使用下面的代码,我只得到一个空白页,名称或昵称不会得到回复。我交叉检查了路径,它仍然正确,它没有回显任何

<?php
$url="http://www.mans-best-friend.org.uk/dog-breeds-alphabetical-list.htm";
$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL,$url);
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1');
$html = curl_exec($curl_handle);
curl_close($curl_handle);
$mydoc = new DOMDocument();
libxml_use_internal_errors(TRUE); //disable libxml errors
if(empty($html)) die("EMPTY HTML");
    $mydoc->loadHTML($html);
    libxml_clear_errors(); //remove errors for yucky html
    $my_xpath = new DOMXPath($mydoc);
    //////////////////////////////////////////////////////
    $nodes = $my_xpath->query( '//*[@id="table94"]/tbody/tr/td' );    
    foreach( $nodes as $node )
    {  
    $title=$my_xpath->query( 'p[@data-iceapc="1"]/span/a/font', $node );
    $nickname=$my_xpath->query( 'p[@data-iceapc="2"]/span/a/font', $node );
    echo $title." ".$nickname."<br>";     
    }
?>

万一找不到p元素。滚动到狗名所在的部分。例如,Affenpinscher右键单击它并选择inspect-它显示p元素。

首先,您必须"修复"xpath的html代码才能正常工作,因为它包含太多错误。在这种情况下,我只提取id为table94的所需表。

之后,您可以在dom对象上使用xpath来获得所需的数据:

<?php
$url="http://www.mans-best-friend.org.uk/dog-breeds-alphabetical-list.htm";
$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL,$url);
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1');
$html = curl_exec($curl_handle);
curl_close($curl_handle);
$html = preg_replace('/^.*(<table[^>]*id="table94">.*?<'/table>).*$/is', ''1', $html);
$mydoc = new DOMDocument();
$mydoc->loadHTML($html);
$my_xpath = new DOMXPath($mydoc);
$nodes = $my_xpath->query( '//tr' );    
foreach( $nodes as $node )
{
    if ($my_xpath->query('td[position()=last()-1]/p/span/a/font', $node)->length > 0) {
        echo $my_xpath->query('td[position()=last()-1]/p/span/a/font', $node)->item(0)->textContent.' ';
        echo $my_xpath->query('td[position()=last()]/p/span/font', $node)->item(0)->textContent."<br />";
    }
}