Eva Lauren Kelly
Eva Lauren Kelly

Reputation: 413

php simplexml get all elements with specific tag

<playlist revision="1">
(...)
<relatedLink>
<id>tag:bbc.co.uk,2008:iplayer:concept_pid:b03tcb0b</id>
<title>MI High: Series 7: The Man Who Drew Tomorrow</title>
<link rel="alternate" href="http://www.bbc.co.uk/iplayer/episode/b03tcb0b/MI_High_Series_7_The_Man_Who_Drew_Tomorrow/"/><link rel="thumb" href="http://ichef.bbci.co.uk/programmeimages/p01q7ysm/b03tcb0b_150_84.jpg" type="image/jpeg" width="150" height="84"/><summary>Children's spy drama. When clairvoyant Derren Beige is kidnapped by KORPS, the spies must race against the clock to decipher the mystery of his ability.</summary>
</relatedLink><relatedLink><id>tag:bbc.co.uk,2008:iplayer:concept_pid:b03qgljm</id><title>MI High: Series 7: The Mayze</title><link rel="alternate" href="http://www.bbc.co.uk/iplayer/episode/b03qgljm/MI_High_Series_7_The_Mayze/"/><link rel="thumb" href="http://ichef.bbci.co.uk/programmeimages/p01phbl5/b03qgljm_150_84.jpg" type="image/jpeg" width="150" height="84"/><summary>Children's spy drama. It's a new term at St Hearts and Frank tasks the elite spies with the mission of tracking down one of Zoe's remaining duplicants.</summary></relatedLink>

I need to get all the relatedLinks and list them using php simplexml. Sorry for the lack of detail, this was quick.

Upvotes: 2

Views: 2033

Answers (2)

Maciek
Maciek

Reputation: 1990

Xpath is also a good option if you want to select all occurrences regardless of position in tree. This cheatsheet can help make your expressions.

$xml=simplexml_load_string($x);
    
foreach($xml->xpath(".//relatedLink") as $rl){
 print_r($rl);
}

Upvotes: 0

michi
michi

Reputation: 6625

This is it:

$xml = simplexml_load_string($x); // assume XML in $x

foreach ($xml->relatedLink as $rl) {
    echo $rl->title . PHP_EOL;
}

see it working: https://eval.in/97004

read the manual: http://www.php.net/manual/en/simplexml.examples-basic.php

Upvotes: 2

Related Questions