XML GET đã sử dụng để lấy các giá trị node từ XML file. Ví dụ sau minh họa cách lấy dữ liệu từ XML.

Tệp note.xml

Tệp note.xml là một xml file, nó có thể được truy cập bởi php file.

<SUBJECT>
   <COURSE>Android</COURSE>
   <COUNTRY>VietNam</COUNTRY>
   <COMPANY>BKcompany</COMPANY>
   <PRICE>$10</PRICE>
</SUBJECT>

Tệp index.htm

Index page có quyền để lấy truy cập xml data bởi sử dụng hàm simplexml_load_file().

<?php
   $xml=simplexml_load_file("note.xml") or die("Error: không thể tạo đối tượng");
?>
<html>
   <head>

      <body>

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

      </body>

   </head>
</html>

Lưu chương trình trên trong một file có tên là test.php trong htdocs, sau đó mở trình duyệt và gõ địa chỉ http://localhost:8080/test.php sẽ cho kết quả:

XML Get trong PHP

Lấy các giá trị node

Bây giờ giả sử note.xml có code như sau:

<?xml version="1.0" encoding="utf-8"?>
<hoclaptrinh>

   <course category="JAVA">
      <title lang="vi">Java</title>
      <tutor>Nguyen Hoang Manh</tutor>
      <duration></duration>
      <price>$30</price>
   </course>

   <course category="Python">
      <title lang="vi">Python</title>.
      <tutor>Tran Phuong Nam</tutor>
      <duration>3</duration>
      <price>$50</price>
   </course>

   <course category="HTML">
      <title lang="vi">html</title>
      <tutor>Tran Minh Chinh</tutor>
      <duration>5</duration>
      <price>$50</price>
   </course>

   <course category="WEB">
      <title lang="vi">Cong nghe web</title>
      <tutor>Hoang Nam</tutor>
      <duration>10</duration>
      <price>$60</price>
   </course>

</hoclaptrinh>

PHP code sẽ là như sau:

<html>
   <body>

      <?php
         $xml=simplexml_load_file("note.xml") or die("Error: không thể tạo đối tượng");
         foreach($xml->children() as $note) { 
            echo $note->title . "<br> "; 
            echo $note->tutor . "<br> "; 
            echo $note->duration . "<br> ";
            echo $note->price . "<hr>"; 
         }
      ?>

   </body>
</html>

Lưu chương trình trên trong một file có tên là test.php trong htdocs, sau đó mở trình duyệt và gõ địa chỉ http://localhost:8080/test.php sẽ cho kết quả:

XML GET trong PHP

Viết câu trả lời

Drop Images

0 Bình luận