Wednesday, February 22, 2012

Read XML data using PHP


Read XML data using PHP
This program will parse XML data using PHP. Create a XML file and load the XML file into your PHP program. This program will extract data from XML file



Step 1 )Create xyx.xml file using below code. And save in same location with your PHP file.

<?xml version="1.0" encoding="iso-8859-1"?>
<?xml-stylesheet type="text/css" href="pqr.css"?>
<person>
   <name>Sourav</name>
   <surname>Kayal</surname>
</person>  

Step 2) Create a PHP file using below code. And run it. It will display the XML file data.

<?php
$doc = new DOMDocument();
$doc->load('xyx.xml');

$employees = $doc->getElementsByTagName( "person" );
foreach( $employees as $employee )
{
$names = $employee->getElementsByTagName("name");
$name = $names->item(0)->nodeValue;

$ages= $employee->getElementsByTagName("surname");
$age= $ages->item(0)->nodeValue;

echo "<b>$name - $age \n</b><br>";
}
?>

3 comments:

  1. Thank you for the xample , but i want to know if is it possible to read the xml file without knowing the TagNames, suppose if i drop a xml file for music , and then next i will drop xml file iwth student data ,,,, for each of these files the TagName will be different and i dont want to hard code th tag names is it possible please help.

    ReplyDelete
  2. Thank you java_object to read my blog.
    As far as my knowledge it's possible to extract data from XML file without using tagname.

    ReplyDelete
  3. Nice site....Please refer this site also Our vision success!Training are focused on perfect improvement of technical skills for Freshers and working professional. Our Training classes are sure to help the trainee with COMPLETE PRACTICAL TRAINING and Real time methodologies
    Dot Net Training in Chennai | Dot Net Training Institute in Chennai
    Software Testing Training in Chennai | Software Testing Course in Chennai
    Java Training Institute in Chennai | Core Java Training in Chennai | Java Course and Certification
    PHP Course in Chennai | PHP Certification in chennai | PHP Training Institutes

    ReplyDelete