We now have a youtube channel. Subscribe!

PHP Simple XML Parser

PHP Simple XML Parser


Hello folks! welcome back to a new edition of our tutorial on PHP. In this tutorial guide, we are going to be studying 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 going to be rounding up for this tutorial post. In our next tutorial, we are going to be discussing about the PHP - Simple XML GET.

Feel free to ask your questions where necessary and we 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.

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.
© 2023 ‧ WebDesignTutorialz. All rights reserved. Developed by Jago Desain