James
James

Reputation: 77

Parsing deep XML with PHP SimpleXML and XPath

PHP noob here. I seem to be misunderstanding how to get the value of an XML node using XPath, and I haven't been able to find a StackOverflow answer that quite address what I'm doing wrong.

So, using RPG Geek's API, I'm trying to pull some information about the game Dread. (Here's a link to the URI.)

$rpggeekXML = simplexml_load_file('https://www.rpggeek.com/xmlapi/boardgame/166952?&stats=1');
$rating = $rpggeekXML->xpath('ratings/average');
$usersrated = $rpggeekXML->xpath('ratings/usersrated');

I know I'm successfully pulling in the rpggeek XML because if I do var_dump($rpggeekXML);, I can see all of the information I'm expecting. However, if I do var_dump($rating); or var_dump($usersrated);, it returns array(0) { }. So it seems I must be screwing up the XPath lines, but I can't figure out how. What am I doing wrong?

Upvotes: 2

Views: 243

Answers (2)

Danijel
Danijel

Reputation: 12699

Use full path to find desired node:

$rating = $rpggeekXML->xpath( 'boardgame/statistics/ratings/average' );

echo $rating[0];

Collect all "average" nodes in document:

$rating = $rpggeekXML->xpath( '//average' );    

echo $rating[0];

Upvotes: 2

Philipp
Philipp

Reputation: 15629

I think you xpath syntax is wrong. You can try this

$rpggeekXML = simplexml_load_file('https://www.rpggeek.com/xmlapi/boardgame/166952?&stats=1');
$rating = $rpggeekXML->xpath('//ratings/average');
$usersrated = $rpggeekXML->xpath('//ratings/usersrated');

Upvotes: 0

Related Questions