0

I have a xml feed that looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<books version="1.0">
<book>
<NR><![CDATA[1]]></NR>
<title><![CDATA[somebook]]></title>
<picture><![CDATA[http://www.website.com/images/somebook_pic.jpg]]></picture>
</book>
</books>

And a php loop that is not working:

<?php
$file = "books.php";
$html = "";
$url = "http://www.website.com/feed/feed.xml";
$xml = simplexml_load_file($url);
for($i = 0; $i < 10; $i++){
$number = $xml->book[$i]->NR;
$img = $xml->book[$i]->picture;
$title = $xml->book[$i]->title;
$html .= "<img src=\"$img\">$title - $number</a>";
}
file_put_contents($file, $html);
?>

It was working when that XML feed was without ![CDATA[, unfortunately they change it (I do not know why) and now it's not working.

XML feed update:

<?xml version="1.0" encoding="UTF-8"?>
<books version="1.4">
<category name="science-fiction">

<book>
<NR><![CDATA[1]]></NR>
<title><![CDATA[somebook]]></title>
<picture><![CDATA[http://www.website.com/images/somebook_pic.jpg]]></picture>
</book>

<book>
<NR><![CDATA[2]]></NR>
<title><![CDATA[somebook2]]></title>
<picture><![CDATA[http://www.website.com/images/somebook2_pic.jpg]]></picture>
</book>

</category>
</books>
Belhor
  • 57
  • 1
  • 11

1 Answers1

0

You're not iterating over the <category> element; this should work:

$books = simplexml_load_string($xml);

$html = '';

foreach ($books->category->book as $book) {
    $html .= sprintf('<img src="%s">%s - %s</a>',
      htmlspecialchars($book->picture, ENT_QUOTES, 'UTF-8'),
      htmlspecialchars($book->title, ENT_QUOTES, 'UTF-8'),
      htmlspecialchars($book->NR, ENT_QUOTES, 'UTF-8')
    );
}

echo $html, PHP_EOL;

Demo

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309