问题
PHP xpath query not working. any idea?
Problem # 1
HTML Source:
<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 i tried:
$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);
}
But nothing came, any help for the right expression for this query?
Problem # 2
i wanted to check if i am getting content, so i tried this and got all href links:
$divs = $xpath->query('//a/@href');
foreach($divs as $b){
print_r($b); // this is line #19
}
I got this error:
DOMAttr Object
Warning: print_r(): Not yet implemented in C:\xampp\htdocs\testing\index.php on line 19
any idea, why i am getting this warning?
Problem # 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>
any idea how can i get this info and convert it to array like this:
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:
Problem #1
Based on your markup, you're trying to target <td>
tags, but in your query, it's //div
, which doesn't make sense. Target <td>
's:
$rows = $xpath->query('//tr/td[@class = "abc pqr xyz"]');
foreach($rows as $b){
echo $b->nodeValue . '<br/>';
}
Sample Output
Problem #2
This is most likely related to this issue:
https://bugs.php.net/bug.php?id=61858&edit=1
Problem #3
You could just continue to use xpath to target the desired values. Select all those <td>
's and from there, just use each of them as the context node:
$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
来源:https://stackoverflow.com/questions/28080875/php-xpath-query-expression-not-working