Showing posts with label XML. Show all posts
Showing posts with label XML. Show all posts

Saturday, 21 January 2012

How to get data from xml in php

1. Put this code in php file 

<?php
 
    $objDOM = new DOMDocument();
    $objDOM->load("test.xml"); //make sure path is correct
   
    $employee = $objDOM->getElementsByTagName("employee");
    // for each employee tag, parse the document and get values for
    // name and designation tag.
   
    foreach( $employee as $value )
    {
        $names = $value->getElementsByTagName("name");
        $name  = $names->item(0)->nodeValue;
       
        $designations = $value->getElementsByTagName("designation");
        $designation  = $designations->item(0)->nodeValue;
       
        echo "$name :: $designation <br><br>";
    }
    echo "<u>Another Way using <strong>simplexml_load_file</strong> php function</u><br><br>";
    $xml = simplexml_load_file("test.xml") or die ("Unable to load XML file!");
   
    // access XML data
    foreach($xml as $xml_value)
    {
        $emp_name = $xml_value->name;
        $emp_designation = $xml_value->designation;
        echo "$emp_name => $emp_designation <br><br>";
    }
?>

2. Here is XML file

<?xml version="1.0" encoding="ISO-8859-1"?>
<company>
  <employee>
    <name>Prashant Chaudhari</name>
    <designation>PHP Web Developer</designation>
  </employee>
  <employee>
    <name>Dhirendra Rathod</name>
    <designation>C#.Net Web Developer</designation>
  </employee>
</company>