-1

I am trying to parse the following xml but my code blew parses the first tag of each section only,

$xml = simplexml_load_string($response);       
foreach ($xml->person as $p) {
  $p = $p->attributes()->name;
  echo "     ".$p. "        ";
}

The output is Joe Ray Alex, but I need it to show the name of every person in the list, so it should be Joe Jack Ray John Edward Alex.

 <?xml version="1.0" encoding="utf-8"?>
 <people>
   <person name="Joe">
   <person name="Jack">
   </person>
   </person>

   <person name="Ray">
   <person name="John">
   <person name="Edward">
   </person>
   </person>

   <person name="Alex">
   </person>
 </people>

Is there any other option rather than changing the xml? because I receive the xml as a response from a web service.

hakre
  • 193,403
  • 52
  • 435
  • 836
Saeed Pirdost
  • 167
  • 3
  • 12

3 Answers3

1
  1. Fix Your XML

  2. IF you really want to print inner element data, you should make a recursive function:

    function printNames($simpleXMLElement) {
    
        // Print the name attribute of each top level element
        foreach ($simpleXMLElement as $element) {
    
            // Print this elements name.
            $p = $simpleXMLElement->attributes()->name;
            echo "     ".$p."        ";
    
            // Send the inner elements to get their names printed
            foreach ($simpleXMLElement->children() as $child) {
                printNames($child);
            }
        }
    }
    
    
    $xml = simplexml_load_string($response);
    printNames($xml);
    
Jormundir
  • 430
  • 4
  • 11
0

Why not correct the XML?

i.e.

<people>
   <person name="Joe" />
   <person name="Jack" />

   <person name="Ray" />
   <person name="John" />
   <person name="Edward" />

   <person name="Alex" />
 </people>
Ed Heal
  • 59,252
  • 17
  • 87
  • 127
0

Given your odd XML structure, you either have to look for and recurse down into any person elements you find, or you need to generate a flat list of all person elements.

Here is an xpath approach:

$people = $xml->xpath('descendant::person');

foreach ($people as $person) {
    echo $person['name'], "\n";
}
Francis Avila
  • 31,233
  • 6
  • 58
  • 96