How to parse XML into php? How to parse XML into php? php php

How to parse XML into php?


<?php$doc = new DOMDocument();$doc->load( 'test1.xml' );//xml file loading here$employees = $doc->getElementsByTagName( "employee" );foreach( $employees as $employee ){  $names = $employee->getElementsByTagName( "name" );  $name = $names->item(0)->nodeValue;  $ages= $employee->getElementsByTagName( "age" );  $age= $ages->item(0)->nodeValue;  $salaries = $employee->getElementsByTagName( "salary" );  $salary = $salaries->item(0)->nodeValue;  echo "<b>$name - $age - $salary\n</b><br>";  }?> 

// the out put like this Mark - 27 - $5000 Jack - 25 - $4000 nav - 25 - $4000


I don't really get your question, but f you want to parse xml using php, you can use the xml extension : http://php.net/manual/en/book.xml.php

You will then be able to print out the data to your liking


Think your XML is lacking a root entry, so, parsing will stick. However, that issue aside, lookup simplexml_load_file and simplexml_load_string. Those are the simplest ways to access XML in a PHP-style structure.

In your XML sample, I've inserted a generic 'records' entry. For example:

$t = <<< EOF<?xml version="1.0" encoding="iso-8859-1"?>    <records>    <employee>          <name>Mark</name>          <age>27</age>          <salary>$5000</salary>    </employee>    <employee>          <name>Jack</name>          <age>25</age>          <salary>$4000</salary>    </employee>    <employee>          <name>nav</name>          <age>25</age>          <salary>$4000</salary>    </employee></records>EOF;$x = @simplexml_load_string( $t );print_r( $x );

Function is warning-suppressed since you probably don't want validation warnings. Anyhow, at this point, the parsed XML will look like this:

SimpleXMLElement Object(    [employee] => Array        (            [0] => SimpleXMLElement Object                (                    [name] => Mark                    [age] => 27                    [salary] => $5000                )            [1] => SimpleXMLElement Object                (                    [name] => Jack                    [age] => 25                    [salary] => $4000                )            [2] => SimpleXMLElement Object                (                    [name] => nav                    [age] => 25                    [salary] => $4000                )        ))