tags:

views:

112

answers:

3
+1  Q: 

Parsing XML in PHP

<?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.

+2  A: 

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']) {
Artem Russakovskii
+4  A: 

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

Mark
+1  A: 

You can use print_r() to debug just about any section of a SimpleXML object.

Jestep
Unless your XML has a namespace, and then you get into a whole other set of nastiness.
Jon Winstanley