PHP $ xpath->查询表达式不起作用

时间:2015-01-22 03:37:02

标签: php html xpath domdocument

PHP xpath查询无法正常工作。任何想法?

问题#1
HTML来源:

<tr>
    <td class="abc pqr xyz">Some contents i want to capture</td>
</tr>
<tr>
    <td class="abc pqr xyz">more content i want to capture too</td>
</tr>
<tr>
    <td class="abc pqr xyz">all row in this table i want to capture</td>
</tr>
<tr>
    <td class="abc pqr xyz">they are all pokemon, i want to capture</td>
</tr>

我试过PHP:

$url = "http://www.example.com/";

$opts = array('http'=>array('header' => "User-Agent:MyAgent/1.0\r\n"));
$context = stream_context_create($opts);
$text = file_get_contents($url,false,$context);

$dom = new DOMDocument();
@$dom->loadHTML($text);
$xpath = new DOMXPath($dom);

$divs = $xpath->query('//div/@class="abc pqr xyz"/');
foreach($divs as $b){
    //echo $b->name.'<br />';
    print_r($b);
}

但是没有任何内容,对此查询的正确表达式有任何帮助吗?


问题#2
我想检查一下我是否收到内容,所以我尝试了这个并获得了所有href链接:

$divs = $xpath->query('//a/@href');
foreach($divs as $b){
    print_r($b); // this is line #19
}

我收到了这个错误:

DOMAttr Object
Warning: print_r(): Not yet implemented in C:\xampp\htdocs\testing\index.php on line 19

任何想法,为什么我收到这个警告?


问题#3

                    <td colspan="2" style="">
                        <h3><a href="http://www.example.com/?id=xx" title="View more">I am not sure about the title</a>

                                <small class="comeoneman andwomen">Not a shoe</span>

                        </h3>

                        <div class="blahblah">This is just blah blah blah</div>                     

                    </td>
                    <td colspan="2" style="">
                        <h3><a href="http://www.example.com/?id=xx" title="View more">I am not sure about the title</a>

                                <small class="comeoneman andwomen">No a shoe</span>

                        </h3>

                        <div class="blahblah">This is just blah blah blah</div>                     

                    </td>

任何想法如何获取此信息并将其转换为数组如下:

array (
  title => I am not sure about the title,
  link => http://www.example.com/?id=xx,
  small => not a shoe,
  blahblah => This is just blah blah blah
)

1 个答案:

答案 0 :(得分:2)

问题#1

根据您的标记,您尝试定位<td>代码,但在您的查询中,它是//div,这没有意义。目标<td>

$rows = $xpath->query('//tr/td[@class = "abc pqr xyz"]');
foreach($rows as $b){
    echo $b->nodeValue . '<br/>';
}

Sample Output

问题#2

这很可能与此问题有关:

  

https://bugs.php.net/bug.php?id=61858&edit=1

问题#3

您可以继续使用xpath来定位所需的值。选择所有<td>,然后从那里,只使用它们作为上下文节点:

$data = array();
$td = $xpath->query('//td');
foreach($td as $b){
    $data[] = array(
        'title' => $xpath->evaluate('string(./h3/a)', $b),
        'link' => $xpath->evaluate('string(./h3/a/@href)', $b),
        'small' => trim($xpath->evaluate('string(./h3/small)', $b)),
        'blahblah' => trim($xpath->evaluate('string(./div[@class="blahblah"])', $b)),
    );
}

Sample Output