English 中文(简体)
PHP - Simple XML GET
  • 时间:2024-12-21

PHP - Simple XML GET


Previous Page Next Page  

XML Get has used to get the node values from xml file. The following example shows, How to get the data from xml.

Note.xml

Note.xml is xml file, It can accessed by php file.

<SUBJECT>
   <COURSE>Android</COURSE>
   <COUNTRY>India</COUNTRY>
   <COMPANY>TutorialsPoint</COMPANY>
   <PRICE>$10</PRICE>
</SUBJECT>

Index.htm

Index page has rights to get access the xml data by using implexml_load_file().

<?php
   $xml = simplexml_load_file("note.xml") or die("Error: Object Creation failure");
?>

<html>
   <head>
      
      <body>
         
         <?php
            echo $xml->COURSE . "<br>";
            echo $xml->COUNTRY . "<br>";
            echo $xml->COMPANY . "<br>";
            echo $xml->PRICE;
         ?>
         
      </body>
      
   </head>
</html>

It will produce the following result −

XML Get

Get Node Values

The below code is having information about how to get node values from xml file and XML should be as follows −

<?xml version = "1.0" encoding = "utf-8"?>
<tutorialspoint>
   
   <course category = "JAVA">
      <title lang = "en">Java</title>
      <tutor>Gopal</tutor>
      <duration></duration>
      <price>$30</price>
   </course>
   
   <course category = "HADOOP">
      <title lang = "en">Hadoop</title>.
      <tutor>Satish</tutor>
      <duration>3>/duration>
      <price>$50</price>
   </course>
   
   <course category = "HTML">
      <title lang = "en">html</title>
      <tutor>raju</tutor>
      <duration>5</duration>
      <price>$50</price>
   </course>
   
   <course category = "WEB">
      <title lang = "en">Web Technologies</title>
      <tutor>Javed</tutor>
      <duration>10</duration>
      <price>$60</price>
   </course>

</tutorialspoint>

PHP code should be as follows

<html>
   <body>
   
      <?php
         $xml = simplexml_load_file("books.xml") or die("Error: Cannot create object");
         
         foreach($xml->children() as $books) { 
            echo $books->title . "<br> "; 
            echo $books->tutor . "<br> "; 
            echo $books->duration . "<br> ";
            echo $books->price . "<hr>"; 
         }
      ?>
      
   </body>
</html>

It will produce the following result −

Node Values Advertisements