Irene T.
Irene T.

Reputation: 1393

Parsing xml with simplexml_load

I am trying to parse an xml but I get a problem while I am trying to fetch image url.

My xml is:

<entry>
<title>The Title</title>
<id>http://example.com/post/367327.html</id>
<summary>Some extra text</summary>
<link rel="enclosure" href="http://example.com/photos/f_0px_30px/image687.jpg" type="image/jpeg"  length="" /> 
</entry>

So far I am using the code below to fetch the other data:

$url = "http://msdssite.com/feeds/xml/myxml.xml";
$xml = simplexml_load_file($url);

foreach($xml->entry as $PRODUCT)
{
$my_title = trim($PRODUCT->title);
$url = trim($PRODUCT->id);
$myimg = $PRODUCT->link;
}

How can I parse the href from this: <link rel="enclosure" href="http://example.com/photos/f_0px_30px/image687.jpg" type="image/jpeg" length="" />

Upvotes: 1

Views: 1523

Answers (3)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

Since it seems that your entries can contain several link tags, you need to check that the type attribute has the value image/jpeg to be sure to obtain a link to an image:

ini_set("display_errors", "On");

$feedURL = 'http://OLDpost.gr/feeds/xml/category-takhs-xatzhs.xml';

$feed = simplexml_load_file($feedURL);

$results = array();

foreach($feed->entry as $entry) {
    $result = array('title' => (string)$entry->title,
                    'url'   => (string)$entry->id);

    $links = $entry->link;
    foreach ($links as $link) {
        $linkAttr = $link->attributes();
        if (isset($linkAttr['type']) && $linkAttr['type']=='image/jpeg') {
            $result['img'] = (string)$linkAttr['href'];
            break;
        }
    }
    $results[] = $result;
}

print_r($results);

Note that using simplexml like that (the foreach loop to find the good link tag) isn't very handy. It's better to use an XPath query:

foreach($feed->entry as $entry) {
   $entry->registerXPathNamespace('e', 'http://www.w3.org/2005/Atom');
   $results[] = array(
     'title' => (string)$entry->title,
     'url'   => (string)$entry->id,
     'img'   => (string)$entry->xpath('e:link[@type="image/jpeg"]/@href')[0][0]
   );
}

Upvotes: 2

user1978142
user1978142

Reputation: 7948

If that's the exact XML, actually there is no need for a foreach. Try this:

$xml = simplexml_load_file($url);

$my_title = (string) $xml->title;
$myimg = (string) $xml->link->attributes()['href']; // 5.4 or above
echo $myimg; // http://example.com/photos/f_0px_30px/image687.jpg

Upvotes: 1

Phongdatgl
Phongdatgl

Reputation: 58

Try:

foreach($xml->entry as $PRODUCT)
{
$my_title = trim($PRODUCT->title[0]);
$url = trim($PRODUCT->id[0]);
$myimg = $PRODUCT->link[0];
}

Upvotes: 0

Related Questions