Reputation:
<?php
$xmlstr = <<<XML
<books>
<book>
<title>Great American Novel</title>
<plot>
Cliff meets Lovely Woman.
</plot>
<success type="bestseller">4</success>
<success type="bookclubs">9</success>
</book>
<book>
<title>Man Bites Dog</title>
<plot>
Reporter invents a prize-winning story.
</plot>
<success type="bestseller">22</success>
<success type="bookclubs">3</success>
</book>
</books>
XML;
?>
<?php
$xml = new SimpleXMLElement($xmlstr);
foreach ($xml->book[0]->success as $success) {
switch((string) $success['type']) {
case 'bestseller':
echo $success, ' months on bestseller list<br />';
break;
case 'bookclubs':
echo $success, ' bookclub listings<br />';
break;
}
}
?>
I have cut at paste this code from a tutorial site, so it works fine. Im trying to alter it for my own means. But I can't get it to do what I want. Im trying to print, all the success types, not just the first instance. This xml feed has only two book, titles, the xml feed i'm trying to parse has many more, but the structure is the same, and the only results I'm getting it to print is 4 and 9, which are the for the first book title.
Upvotes: 1
Views: 279
Reputation: 985
You can use print_r() to debug just about any section of a SimpleXML object.
Upvotes: 1
Reputation: 6254
This line is your problem:
foreach ($xml->book[0]->success as $success)
Your referencing the first element of booth array with "book[0]". You will need to change this to something like:
foreach ($xml->book as $book) {
foreach($book->success as $success) {
// switch/case goes here
}
}
Also, side note, make sure each line of code you type on stackoverflow is indented with 4 spaces or more, so the site realizes it is code and doesn't munge it
Upvotes: 4
Reputation: 22023
Your code only iterates through the first book (book[0]). You need to modify it to iterate through all books first.
foreach ($xml->book as $book){
foreach ($book->success as $success) {
switch((string) $success['type']) {
Upvotes: 2