Working with PHP and XML

This article gives you an understanding that how can we read a XML Document in PHP.
first we have an idea that what is XML? Xml is a data storage format. It makes a choice for user to define tags and attributes. A simple structure of an xml document is:

<?xml  version="1.0" ?>
 <data>
   <employee>
      <name>abc</name>
      <salary>10000</salary>
   </employee>
 </data>
OR
<?xml  version="1.0" ?>
<data>
  <employee name=”abc” salary=”10000” />
 </data>

In this xml document parent tag is and its child tags , which has a set of information and tags. And in second example we can use attributes to an xml tags as key/value pair. Now to parse this xml document php has a SimpleXML extension tool.

// storing xml as a string variable
$xml_string = "<?xml  version='1.0' ?>
 <data>
  <employee>
  <name>abc</name>
  <salary>10000</salary>
  </employee>
  </data>";
$xmlObj = simplexml_load_string($xml_string);

simplexml_load_string() is a php function for parsing XML Document. From this xml object $xmlObj we can get employee name and salary

$name = $xmlObj->employee->name;
$salary = $xmlObj->employee->salary;
echo "Name is:".$name."<br /> Salary is:".$salary;
// OR
//If we want data from attributes use:
foreach($xmlObj->employee[0]->attributes() as $key => $value)
{
    echo $key,'="',$value,"\"\n";
}

In this example $a print attribute name”abc” $b its value “10000”. This is a simple description how php interacts with xml. Last there are some illegal XML characters that cannot be parsed by xml are: [<, > &, ‘, “]. So keep in mind when creating xml document.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload the CAPTCHA.



nike tn pas cher tn pas cher peuterey outlet piumini peuterey outlet spaccio peuterey outlet peuterey outlet piumini peuterey outlet spaccio peuterey outlet hogan outlet scarpe hogan outlet hogan outlet online peuterey outlet piumini peuterey outlet spaccio peuterey outlet hogan outlet scarpe hogan outlet hogan outlet online hogan outlet scarpe hogan outlet hogan outlet online doudoune moncler pas cher moncler pas cher doudoune moncler hogan outlet scarpe hogan outlet hogan outlet online nike tn pas cher tn pas cher