SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Jun 2008
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    loop through XML and group by

    Hi, I am new to XML. I really hope someone can help. I am using xml and php 4. i would like to loop through and display the xml data but group by attribute type. so for example i would like it to look like this;

    Movie = James Bond, Jason Bourne
    Book = Lindsay Ford

    Here is an example of my XML;

    <favorites>
    <interesting>
    <type category ="Movie">
    <character>James Bond</character>
    <name>Casino Royale</name>
    </interesting>
    <interesting>
    <type category ="Movie">
    <character>Jason Bourne</character>
    <name>Bourne Identity</name>
    </interesting>
    <interesting>
    <type category ="Book">
    <character>Lindsay Ford</character>
    <name>Shantaram</name>
    </type>
    </interesting>
    </favorites>

    Thank you to everyone

  2. #2
    SitePoint Enthusiast
    Join Date
    Sep 2006
    Location
    UK
    Posts
    91
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    <favorites>
    <interesting>
    <type category ="Movie">
    <character>James Bond</character>
    <name>Casino Royale</name>
    </interesting>
    <interesting>
    <type category ="Movie">
    <character>Jason Bourne</character>
    <name>Bourne Identity</name>
    </interesting>
    <interesting>
    <type category ="Book">
    <character>Lindsay Ford</character>
    <name>Shantaram</name>
    </type>
    </interesting>
    </favorites>
    I recently had a very similar requirement and eventually got somewhere with this which I hope I'm adapting correctly to cover your requirement

    The following is using php:

    PHP Code:
    $url=simplexml_load_file($your_xml);
    //find out the number of type nodes
    //this is the trunk point where the 'category' attribute can have different values 
    $noTypes=count($url->favorites>interesting->type);
    //loop through each of the type nodes using the following count as control
    $i=0;
    foreach (
    $url->favorites->interesting->type as $type) {
    //following means type[0] are the movies type[1] the books
    foreach ($type->attributes() as $typeName=>$typeValue) {
    foreach (
    $url->favorites->interesting->type[$i] as $nodes) { 
    echo 
    $nodes->character;
    echo 
    $nodes->name;
    }
    $i++; 
    }



Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •