Thursday, October 15, 2020

PHP Simple XML Parser



Hello folks! welcome to another section of my tutorial on PHP. In this section of my PHP tutorial, we will be discussing about the PHP Simple XML Parser. 

The simple xml parser is used to parse Names, attributes, and textual contents.

Simple XML Functions

Simple xml functions are shown below -

simplexml_load_file()

This function accepts file path as a first parameter and its very compulsory.

simplexml_load_file(($fileName,$class,$options,$ns,$is_prefix)

simplexml_load_string()

This function accepts the string instead of file reference.

simplexml_load_string($XMLData,$class,$options,$ns,$is_prefix)


simplexml_import_dom()

This xml function accepts Dom formatted xml content and then converts into simple xml.

simplexml_load_string($DOMNode,$class)

Example

The below example shows how to parse an XML data file -

<?php
   $data = "<?xml version = '1.0' encoding = 'UTF-8'?>
   
   <note>
      <Course>Web Development</Course>
      <Subject>HTML</Subject>
      <Company>Web Design Tutorialz</Company>
      <Price>$20</Price>
   </note>";
   
   $xml = simplexml_load_string($data) or die("Error: Cannot create object");
?>
<html>

   <head>
      <body>
         
         <?php
            print_r($xml);
         ?>
      
      </body>
   </head>
   
</html>

Output

When the above code is executed, it will produce the following result -

SimpleXMLElement Object ( [Course] => Web Development [Subject] => HTML [Company] => Web Design Tutorialz [Price] => $20 )

We can also call an xml data file as shown below and it produces the same result as shown above -

<?php
   $xml = simplexml_load_file("data") or die("Error: Cannot create object");
   print_r($xml);
?>


Alright guys! This is where we are rounding up for this tutorial post. In my next tutorial guide, we are going to be discussing about PHP - Simple XML GET.

Feel free to ask your questions where necessary and i will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.
Share:

0 comments:

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.