PHP xml_parse_into_struct() function

Definition and usage

The xml_parse_into_struct() function parses XML data into an array.

This function parses XML data into 2 arrays:

  • Value array - Contains data from the parsed XML
  • Index array - Contains pointers to the positions of values in the Value array

If successful, the function returns 1. Otherwise, it returns 0.

Syntax

xml_parse_into_struct(parser,xml,value_arr,index_arr)
Parameter Description
parser Required. Specifies the XML parser to be used.
xml Required. Specifies the XML data to be parsed.
value_arr Required. Specifies the target array for XML data.
index_arr Optional. Specifies the target array for index data.

Tips and notes

Note:xml_parse_into_struct() returns 0 on failure, 1 on success. This is different from false and true, and attention should be paid when using operators like ===.

Example

XML file:

<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>

PHP code:

<?php
//Invalid xml file
$xmlfile = 'test.xml';
$xmlparser = xml_parser_create();
// Open file and read data
$fp = fopen($xmlfile, 'r');
$xmldata = fread($fp, 4096);
xml_parse_into_struct($xmlparser,$xmldata,$values);
xml_parser_free($xmlparser);
print_r($values);
?>

Output:

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