ฟังก์ชัน xml_parse_into_struct() ของ PHP

คำนิยามและการใช้งาน

ฟังก์ชัน xml_parse_into_struct() จะแปลงข้อมูล XML สู่ตัวแปร

ฟังก์ชันนี้จะแปลงข้อมูล XML สู่ 2 ตัวแปร:

  • Value ตัวแปร - มีข้อมูลจาก XML ที่ถูกแปลง
  • Index ตัวแปร - มีข้อมูลบุนท์ที่มีความหมายต่อค่าใน Value ตัวแปร

ถ้าสำเร็จ ฟังก์ชันนี้จะกลับค่า 1 และไม่สำเร็จก็กลับค่า 0

รูปแบบการใช้

xml_parse_into_struct(parser,xml,value_arr,index_arr)
ตัวแปร คำอธิบาย
parser จำเป็น
xml จำเป็น
value_arr จำเป็น
index_arr ตัวเลือกได้

คำแนะนำและหมายเหตุ

หมายเหตุ:xml_parse_into_struct() ถ้าล้มเหลวก็กลับค่า 0 และสำเร็จก็กลับค่า 1 นี้แตกต่างจาก false และ true ต้องระวังในการใช้เครื่องมือเช่น ===

ตัวอย่าง

ไฟล์ XML:

<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>George</to>
<from>John</from>
<heading>คำเตือน</heading>
<body>ละเมิดการประชุม!</body>
</note>

PHP รหัสโค้ด:

<?php
// อ่าน xml ไม่ได้
$xmlfile = 'test.xml';
$xmlparser = xml_parser_create();
// เปิดและอ่านข้อมูล
$fp = fopen($xmlfile, 'r');
$xmldata = fread($fp, 4096);
xml_parse_into_struct($xmlparser,$xmldata,$values);
xml_parser_free($xmlparser);
print_r($values);
?>

ออกแบบ:

Array
(
[0] => Array
  (
  [tag] => NOTE
  [type] => open
  [level] => 1
  [value] =>
  )
  [1] => Array
    (
    [tag] => TO
    [type] => complete
    [level] => 2
    [value] => George
    )
[2] => Array
  (
  [tag] => NOTE
  [value] =>
  [type] => cdata
  [level] => 1
  )
  [3] => Array
    (
    [tag] => FROM
    [type] => complete
    [level] => 2
    [value] => John
    )
[4] => Array
  (
  [tag] => NOTE
  [value] =>
  [type] => cdata
  [level] => 1
  )
  [5] => Array
    (
    [tag] => HEADING
    [type] => complete
    [level] => 2
    [value] => Reminder
    )
[6] => Array
  (
  [tag] => NOTE
  [value] =>
  [type] => cdata
  [level] => 1
  )
  [7] => Array
    (
    [tag] => BODY
    [type] => complete
    [level] => 2
    [value] => Don't forget the meeting!
    )
[8] => Array
  (
  [tag] => NOTE
  [value] =>
  [type] => cdata
  [level] => 1
  )
[9] => Array
  (
  [tag] => NOTE
  [type] => close
  [level] => 1
  )
)