سؤال

How do I loop through this xml and get the attribute href of the second <link> tag? The one with the attribute rel="enclosure"

This is the XML;

  <entry>
    <link rel="alternate" type="text/html" href="http://www.flickr.com/photos/dax/5495234222/in/set-756787626064123145/"/>
    <link rel="enclosure" type="image/jpeg" href="http://farm6.staticflickr.com/5012/5485746322_9821c561bf_b.jpg" />
  </entry>

This is the php script so far:

<?php
foreach ($feed->entry as $item) {
    $photo = $item->link['href'];
    ?>
    <div class="">
    <a href="<?php print $photo; ?>" class="colorbox-load"><img class="img-responsive" src="<?php print $photo; ?>"></a>
    </div>

<?php
}
?>

This is working apart form the fact it prints the href of the first <link> which is not the one I need.

هل كانت مفيدة؟

المحلول

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-attributelike this:

foreach ($xml->entry as $entry) {

    if ($entry->link['rel'] == 'enclosure') {

        echo "This is the link: " . $entry->link['href'];
    }
}

نصائح أخرى

Use SimpleXML to parse your XML:

<?php
$xml = <<<XML
  <entry>
    <link rel="alternate" type="text/html" href="http://www.flickr.com/photos/dax/5495234222/in/set-756787626064123145/"/>
    <link rel="enclosure" type="image/jpeg" href="http://farm6.staticflickr.com/5012/5485746322_9821c561bf_b.jpg" />
  </entry>
XML;

$links = new SimpleXMLElement($xml);
echo $links->link[1]['href'];
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top