The xml data looks like this:
<feed>
<entry>
<id>12345</id>
<title>Lorem ipsum</title>
<link type="type1" href="https://foo.bar" />
<link type="type2" href="https://foo2.bar"/>
</entry>
<entry>
<id>56789</id>
<title>ipsum</title>
<link type="type2" href="https://foo4.bar"/>
<link type="type1" href="https://foo3.bar" />
</entry>
</feed>
I want to select the content of the href attribute from a link with certain type. (note that type 1 is not always the first link)
Part of the code that works:
for($i=0; $i<=5; $i++) {
foreach($xml->entry[$i]->link as $a) {
if($a["type"] == "type2")
$link = (string)($a["href"]);
}
}
However, I wonder if there is a faster and more elegant solution to this that does not require a foreach loop. Any ideas?
Have you tried using xpath? http://php.net/manual/en/simplexmlelement.xpath.php
This will allow you to do a search for nodes with the specified tag/attribute.
// Updated
You can skip the for loop if you are interested in only the first value. The
xpathfunction returns an array ofSimpleXmlElementobjects so you can use index0to retrieve the first element, and then it’s property.Note – If the element is missing or cannot be found, the
xpathelement will returnfalse, and the below code will error. The code is for illustration only, so you should verify error checking when implementing it.