use simplexml
and xpath
to select an attribute based on another attribute.
xpath
is like an SQL-query for XML:
$xml = simplexml_load_string($x); // assume XML in $x
$link = (string)$xml->xpath("/entry/link[@rel = 'enclosure']/@href")[0];
The [0]
at the end of line 2 requires PHP >= 5.4. If you are on a lower version, either update or do:
$link = $xml->xpath("/entry/link[@rel = 'enclosure']/@href");
$link = (string)$link[0];
The xpath
-expression selects the href
-attributes of all <link>
-nodes that have an attribute rel='enclosure'
and have <entry>
as their parent in an array
of simplexml Elements
.
The code above will select only the 1st element of the array
and transform it to string
.
see it working: https://eval.in/107641
If you rather want to use the foreach
-loop, you need to check for the rel-attribute
like this:
foreach ($xml->entry as $entry) {
if ($entry->link['rel'] == 'enclosure') {
echo "This is the link: " . $entry->link['href'];
}
}