somejkuser
somejkuser

Reputation: 9040

Xpath query assistance nested anchor href extract

Here is my code:

$text = '<div class="cgus_post"><a href="?p=15055">Hello</a></div>';
$dom = new DomDocument();
$dom->loadHTML($text);
$classname = 'cgus_post';
$finder = new DomXPath($dom);
$nodes = $finder->query('//div[class="cgus_post"]//@href');

I'm trying to get the href text for an anchor link within the div cgus_post. What's wrong with my query?

Upvotes: 0

Views: 758

Answers (2)

paul trmbrth
paul trmbrth

Reputation: 20748

probably a missing "@"

'//div[@class="cgus_post"]//@href'

Upvotes: 2

Marc B
Marc B

Reputation: 360592

XPath is incorrect. It should be:

//div[@class="cgus_post"]/a

Then $nodes will be a list of all <a> tags inside a <div class="cgus_post">, and you get their hrefs with

foreach($nodes as $node) {
   $href = $node->getAttribute('href');
}

Upvotes: 0

Related Questions