Rain_xx
Rain_xx

Reputation: 25

Parse XML: Get child nodes for each parent node

I tried a lot of different solutions but I'm just new at this..

I have an xml tree like this:

<book>
  <author> First author </author>
  <title> aaaa </title>
  <price> 111 </price>
</book>
<book>
  <author> Second author </author>
  <title> bbbb </title>
  <price> 222 </price>
</book>
<book>
  <author> Third author </author>
  <title> cccc </title>
  <price> 333 </price>
</book>`

I need to parse it in my php code to obtain a table such as

First author,
aaaa,
111

Second author,
bbbb,
222

Third author,
cccc,
333 

Is it possible? Really thank you.

Upvotes: 2

Views: 1155

Answers (1)

Cyclonecode
Cyclonecode

Reputation: 29991

You could use the DOMDocument class to parse your xml, notice that the xml needs to be valid:

// create a DOMDocument object and load your xml data
$doc = new DOMDocument();
$doc->loadXML($xmlString);

// get all book sections
$books = $doc->getElementsByTagName('book');

// loop through each item and display information
foreach ($books as $book) {
    print $book->getElementsByTagName('author')->item(0)->nodeValue . ',<br />';
    print $book->getElementsByTagName('title')->item(0)->nodeValue . ',<br />';
    print $book->getElementsByTagName('price')->item(0)->nodeValue . '<br /><br />';
}

To load the xml data from a file you could use DOMDocument::load()

A simpler way to do the same would be to use SimpleXML:

// create a SimpleXMLElement
$xmlDoc = simplexml_load_string($xmlString);

// get all children of the first element
$books = $xmlDoc->children();

// loop through each item and display information
foreach ($books as $book) {
    print $book->author . ',<br />';
    print $book->title . ',<br />';
    print $book->price . '<br /><br />';
}

Notice that the second example will only work if your xml is considered to be well formed, you could wrap your current markup between <books></books>:

<books>
  <book>
    <author> First author </author>
    <title> aaaa </title>
    <price> 111 </price>
 </book>
 ...
</books>

Upvotes: 2

Related Questions