PHP - 简单的 XML GET


XML Get 用于从 xml 文件中获取节点值。下面的例子展示了如何从xml中获取数据。

注释.xml

Note.xml是xml文件,可以通过php文件访问。

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

索引.htm

索引页有权使用implexml_load_file()来访问xml数据。

<?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>

它将产生以下结果 -

XML获取

获取节点值

下面的代码包含有关如何从 xml 文件获取节点值的信息,XML 应如下所示 -

<?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代码应该如下

<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>

它将产生以下结果 -

节点值