Sunday, 12 April 2015

Reading- XML -File- using- PHP

(1)Write code for   employee.xml   file:


<?xml version="1.0" encoding="iso-8859-1"?>

<employees>

  <employee>

  <name>Mark</name>

  <age>27</age>

  <salary>$5000</salary>

  </employee>

  <employee>

  <name>Jack</name>

  <age>25</age>

  <salary>$4000</salary>

  </employee>

  </employees>


(2)write code for php file  readxml.php  :


<?php


$doc = new DOMDocument();  //declare a object


$doc->load( 'employee.xml' );  // load xml file


 
$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>";

  }

?>

(3)run php file  & output will be:

Mark - 27 - $5000 
Jack - 25 - $4000 


No comments:

Post a Comment