XML display nods from certain category PHP



I have a xml file that looks like that one:



<response>

<books>
<link>http:/www.website.com/linktobook/1.html</link>
<title>Book Title 1</title>
<image>http:/www.website.com/linktobook/1.jpg</image>
<category>b</category>category>
</books>

<books>
<link>http:/www.website.com/musicdvd/2.html</link>
<title>Music DVD 1</title>
<image>http:/www.website.com/musicdvd/2.jpg</image>
<category>m</category>category>
</books>

<books>
<link>http:/www.website.com/linktobook/3.html</link>
<title>Book Title 3</title>
<image>http:/www.website.com/linktobook/3.jpg</image>
<category>b</category>category>
</books>

</response>


What I want do to is to generate files in for loop (this is working) but only for nodes from certain category (in this example category "b" as books).


This is my PHP script:



<?php
$html = "";
$url = "http://ift.tt/1vSy1n2";
$xml = simplexml_load_file($url);
for($i = 0; $i < 10; $i++){
${"file$i"} = "file$i.php";
$cat = $xml->books[$i]->category;
if ($cat == "b") {
$link = $xml->books[$i]->link;
$title = $xml->books[$i]->title;
$html .= "<a href=\"$link\">$title</a>";
file_put_contents(${"file$i"}, $html);
} else {
$i--;
}
}
?>


Now file0.php is OK and looks like this:



<a href="http:/www.website.com/linktobook/1.html">Book Title 1</a>


But file1.php have 2 nodes insiad and looks like this:



<a href="http:/www.website.com/linktobook/1.html">Book Title 1</a>
<a href="http:/www.website.com/linktobook/2.html">Book Title 2</a>


file2.php looks like this:



<a href="http:/www.website.com/linktobook/1.html">Book Title 1</a>
<a href="http:/www.website.com/linktobook/2.html">Book Title 2</a>
<a href="http:/www.website.com/linktobook/3.html">Book Title 3</a>


And so on. But I want to have only one node in every file.


No comments:

Post a Comment