DOMXPath $html->query('//p[@class="myclass"]/a')->item(0); not working
DOMXPath $html->query('//p[@class="myclass"]/a')->item(0);
is not working.
Here is the HTML:
<p class="username">
<img src="http://static1.tryal.com/img/b.gif" onclick="lalalaa()" class="a12s_iYblt4hN_DkIt_GoiyOtu8 opsi" />
<b>
<a href="/about"><b>Lalala.</b></a>
</b>
</p>
$name = $开发者_StackOverflow社区html->query('//p[@class="username"]/a')->item(0)->nodeValue;
//This doesn't return the name "Lalala.";
$name = $html->query('//p[@class="username"]')->item(0)->nodeValue;
//This works just fine.
Why isn't this tree working? Am I typing it wrong?
Thank you very much in advance.
The xpath you have specified didn't provide any result (or an result with no elements to be precise). You can fix that by not letting the b
element slip through:
$name = $html->query('//p[@class="username"]/b/a')->item(0)->nodeValue;
^^^
or by not making a
a direct/immediate child from p
but somewhere deeper as well (descendant of, double slash //
in xpath):
$name = $html->query('//p[@class="username"]//a')->item(0)->nodeValue;
^^
Try
$name = $html->query('//p[@class="username"]//a')->item(0)->nodeValue;
You are looking for 'a' child of (single slash) 'p', while what you want I understand is 'a' descendant of (double slash) 'p'
精彩评论