简体   繁体   中英

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 = $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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM