Using Simple XML Parser in PHP

coding-zon-xml-parser


How to use Simple XML Parser in PHP

Simple XML is an extension that allows us to easily manipulate and get XML data using PHP. From PHP 5, It is a part of the PHP core. Before going to learn about Simple XML Parser in PHP.  Let's have some brief introduction of XML.

What is XML?

The Extensible Markup Language (XML) is a simple text-based format for porting structured information like documents, data, books, transactions, invoices, configuration  and much more from one end to another both locally and across networks. It was derived from an older standard format called SGML, in order to be more suitable for modern days Web use. XML is similar to HTML. It uses opening and closing tags. Unlike HTML, XML allows users to define their own tags.

Go toTOP

What is XML Used For?

XML is one of the most widely-used formats for sharing structured information between programs, between people.



Types of XML

  • Tree based
  • Event based


XML Parse Extensions:

 The following XML parsers are available in the PHP core.

  1. Simple XML parser
  2. DOM XML parser
  3. XML parser
  4. XML Reader


1. Simple XML parser

It is tree based XML parser and is used to parse Name, attributes and textual content. The simple XML functions are shown below…

 

 

  • simplexml_load_file():   This function accepts file path as a first parameter.
  • simplexml_load_string(): This function accepts the string instead of file reference.
  • simplexml_import_dom(): Accepts DOM formatted XML content, and it converts into simple XML.


The following code to get the node values from XML file.

 Go to个

 sample.xml

<?xml version = '1.0' encoding = 'UTF-8'?> <courses> <Course>WebDeveloper</Course> <Subject>PHP</Subject> <Company>e-Trainings</Company> <Price>$100</Price> </courses>


 

 

 

 readxml-file.php

<?php $xml = simplexml_load_file("sample.xml") or 
 die("Error: Object Creation failure"); print_r($xml); //prints $xml Object //reading each element value from node of an Object echo "<h2>Course Details</h2>"; echo "Course:". $xml->Course."<br /> "; echo "Subject:". $xml->Subject."<br /> "; echo "Company:". $xml->Company."<br /> "; echo "Price:". $xml->Price; ?> 
 
 

 

 

 

 

Result:

e-trainings-php-readxml-file-example

 Parses XML data string

The following code parses XML data string

 

 Go top menu个

 readxml-string.php


<?php $data = "<?xml version = '1.0' encoding = 'UTF-8'?> <note> <Course>WebDeveloper</Course> <Subject>PHP</Subject> <Company>e-Trainings</Company> <Price>$100</Price> </note>"; $xml = simplexml_load_string($data) or die("Error: Cannot create object"); //reading each element value from node of an Object echo "<br /> "; echo $xml->Course."<br /> "; echo $xml->Subject."<br /> "; echo $xml->Company."<br /> "; echo $xml->Price; ?>






 

 

 

 

 



 

Result:


e-trainings-php-readxml-string-example 

TOP MenuP



 

Parses XML data file

sample2.xml



<?xml version="1.0" encoding="utf-8"?> <courses> <course category="WEB"> <title>PHP Developer</title> <subject>PHP</subject> <company>e-Trainings</company> <price>$100</price> </course> <course category="Programing"> <title>Python Programmer</title> <subject>Python2.7</subject> <company>e-Trainings</company> <price>$150</price> </course> <course category="UI"> <title>JQuery Scripting</title> <subject>JQuery </subject> <company>e-Trainings</company> <price>$75</price> </course> </courses>
 
 
 
 
 
 












 

 

  Move toTOP

 

index.php

<?php echo '<h2>PHP SimpleXML - Reading Specific Node Elements </h2>'; $xml=simplexml_load_file("sample2.xml") or die("Error: Cannot create object"); echo $xml->course[0]->title . ", "; echo $xml->course[0]->subject . ", "; echo $xml->course[0]->company . ", "; echo $xml->course[0]->price . "<br>"; echo '<h2>PHP SimpleXML - Reading each Node Values - Loop</h2> '; foreach($xml->children() as $node) { echo $node->title . ", "; echo $node->subject . ", "; echo $node->company . ", "; echo $node->price . "<br>"; } echo '<h2>PHP SimpleXML - Reading Attribute values of all Nodes</h2> '; foreach($xml->children() as $node) { echo $node[0]['category']." "; } echo '<h2>PHP SimpleXML - Get Node and Attribute Values Loop </h2> '; foreach($xml->children() as $node) { echo '<br><b>'.$node[0]['category']."</b></br> "; echo $node->title . ", "; echo $node->subject . ", "; echo $node->company . ", "; echo $node->price . "<br>"; } 
 
 
 
 
 
 
 
 
 
 
 
 
 





















 

 ?>
 



e-trainings-php-readxml-nodes-attributes-example


Go TOP

 

Error Handling

Error Handling: Use the libxml functionality to retrieve all XML errors 
when loading the document and then iterate over the errors. 
Below example tries to load a broken XML string:
 
 
 




<?php
libxml_use_internal_errors(true);
$myXMLData =
"<?xml version='1.0' encoding='UTF-8'?>
<document>
<user>John Doe</wronguser>
<email>john@example.com</wrongemail>
</document>";

$xml = simplexml_load_string($myXMLData);
if ($xml === false) {
  echo "Failed loading XML: ";
  foreach(libxml_get_errors() as $error) {
    echo "<br>", $error->message;
  }
} else {
  print_r($xml);
}
?>











 

How to Convert XML to an Array With PHP


This example  performing  3 steps. To convert XML to PHP array.


Step1 - loading XML

Loading XML file using simplexml_load_string()

Step2 - XML to JSON conversion

Converting XML to JSON object using :  json_encode()

Step3 - JSON to array conversion

Converting JSON object to PHP array using:  json_decode()

The json_decode() function returns an object by default. The json_decode() function has a second parameter, and when set to true, JSON objects are decoded into associative arrays.

TOP

xml2array.php

<!DOCTYPE html>
<html>
<body>

<?php
$myXMLData =
"<?xml version='1.0' encoding='UTF-8' ?>
<xml>
<products>
<product> 
<title>product1</title> 
<description>Product one desc </description> 
</product> 
<product> 
<title>product2</title> 
<description>Product two desc </description> 
</product>  
</products>
</xml>";

echo '<h2>How to Convert XML to an Array With PHP</h2>';

$xml=simplexml_load_string($myXMLData) or die("Error: Cannot create object");

if ($xml === FALSE) {
    echo "There were errors parsing the XML file.\n";
    foreach(libxml_get_errors() as $error) {
        echo $error->message;
    }
exit;
}

$jsonobj = json_encode($xml);
$array = json_decode($jsonobj,TRUE); 


foreach($array['products'] as $key => $value) {


    foreach($value as $k => $val){
    
        foreach($val as $i => $j){
        print   $i. " = ".$j."<br />";
        }
    echo "<hr />";
    }
}

?>
</body>
</html> 
 
 
 
 
 
 
 
 
 








e-trainings-php-simplexmlparser-xml-to-array-example









Comments

Popular posts from this blog

Recently viewed list in PHP Mysql

Import CSV File Into MySQL Using PHP

Shoppingcart using PHP Sessions - Miniproject