Wednesday, January 1, 2014

How to read XML file in PHP

How to read XML file in PHP?

This article explains you how to read XML file in PHP
Read xml file in PHP

Usage of XML Documents

XML stands for Extensible Markup Language. XML files can be use to transfer and store data. XML files are both human and machine readable. XML data is stored in plain text format. Also XML documents are platform independent. XML tags are not predefined. You can use your custom tags to form a XML document. So it is very easy to create XML file for your requirement. RRS feeds and Web Services use XML for data transfer. Some applications store there configurations in XML files. For a example ASP.Net web.config file is an XML document. Both web applications and desktop applications use XML for transfer and store data. There can be small XML files and very large files up to several Gigabytes.

Download source code for read XML file

Reading XML file using PHP.

In most case you may need to read XML files. Suppose that you have to fetch product catalogue into database. All product details are provided using an XML file. Bellow example will show how to read simple XML file using PHP.

1.) How to read product catalogue XML in PHP.

Before you start reading XML file, please download the file here. Bellow example depends on the above XML file. That file contains sample product catalogue with three products. In this example I have used HTML table to view the products in the XML file.

date_default_timezone_set("Asia/Colombo"); error_reporting(-1);//Display All errors and warnings

$xml_file_path = "products.xml"; $elements = array('id','name','category','manufacture','available');//XML nodes

if(file_exists($xml_file_path)){ echo '<table border=\'1\'><tr>'; foreach($elements as $th){ echo '<th>'.ucfirst($th).'</th>'; }
echo '</tr>';
$xml_doc = new DOMDocument();

$products = $xml_doc->getElementsByTagName("product"); $total_products = $products->length;

foreach ($products as $product){
echo '<tr>';
foreach($elements as $element){ echo '<td>'.getNodeValue($product,$element).'</td>'; } echo '</tr>'; } echo '</table>'; echo '<p>'.$total_products.' products in the XML file</p>'; }else{ exit("XML file does not exists"); }

function getNodeValue(&$DOMElement,$nodeName){ if($DOMElement->getElementsByTagName($nodeName)->length==1){ return $DOMElement->getElementsByTagName($nodeName)->item(0)->nodeValue; }else{ return NULL; } }

2.) Read XML file and insert data to MySQL database using PHP.

Sometimes you may need to insert data in a XML file in to database table. In this example I will explain you how to read XML file and insert data in to the database using our products.xml file. First of all you have to create a table to store products.

Table Structure

  CREATE TABLE `product` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`category` varchar(100) DEFAULT NULL,
`manufacture` varchar(255) DEFAULT NULL,
`qty` int(11) DEFAULT NULL,
PHP code to import data:

date_default_timezone_set("Asia/Colombo"); error_reporting(-1);

$xml_file_path = "products.xml";

$dbCon = new mysqli('localhost', 'root', '1234', 'test', 3306);//Database Connection $xml_doc = new DOMDocument(); $xml_doc->load($xml_file_path);

$products = $xml_doc->getElementsByTagName("product"); $insertCount = 0;

foreach ($products as $product){
$sql="INSERT INTO product(" . "name," . "category," . "manufacture," . "qty" . ")" . "VALUES(" . "'".$dbCon->escape_string(getNodeValue($product,'name'))."'," . "'".$dbCon->escape_string(getNodeValue($product,'category'))."'," . "'".$dbCon->escape_string(getNodeValue($product,'manufacture'))."'," . "".(int)getNodeValue($product,'available')."" . ")";
$dbCon->query($sql); $insertCount++; }
$dbCon->close(); echo '<p>'.$insertCount.' products fetched in to the database</p>'; }else{ exit("XML file does not exists"); }

function getNodeValue(&$DOMElement,$nodeName){ if($DOMElement->getElementsByTagName($nodeName)->length==1){ return $DOMElement->getElementsByTagName($nodeName)->item(0)->nodeValue; }else{ return NULL; } } ?>

Download source code for parse XML file and insert into MySQL Database

Note: You may need to check if the product already exists in the database before import each product. Above script simply insert all products into database without check duplicates.
If you have large XML files, It may took long time to complete the inset. So PHP will give a time out error. In such case you have to manually set the time limit to zero by using set_time_limit(0); zero means no time limit. Script will be execute until it completes the data fetch. Default PHP time limit is 30 seconds. You can set preferred value for it without changing the php.ini file using above function.