PHP | xml_parse_into_struct() Function - GeeksforGeeks

07 Aug, 2021
The xml_parse_into_struct() function is an inbuilt function in PHP which is used to parse XML data into an array structure. The XML data are parsed into two parallel array structures, first one is index array that contains pointers to the location of the values in the value array and second one is value array that contains the data from the parsed XML.
Syntax: 
int xml_parse_into_struct( resource $xml_parser, string $data,
                                        array $values, array $index )
Parameters: This function accepts four parameters as mentioned above and described below:  
$xml_parser: It is required parameter. It holds the reference of XML parser.
$data: It is required parameter. It holds the string which contains XML data.
$values: It is required parameter. It holds the array containing the values of the XML data.
$index: It is optional parameter. It specifies an array with pointers to the location of the values in $values.
Return Value: This function returns 1 on success and 0 on failure. It is not same as True and False.
Note:  
This function is available for PHP 4.0.0 and newer version.
These examples may not work on online IDE. So, try to run it on local server or php hosted servers.
gfg.xml file:  
XML
<?xml version="1.0" encoding="utf-8"?><user>    <username> user123 </username>    <name> firstname lastname </name>    <phone> +91-9876543210 </phone>    <detail> I am John Doe. Live in Kolkata, India. </detail></user>
Program 1: 
PHP
<?php // Create an xml parser$xml_parser = xml_parser_create(); // Opening xml file in file stream$filePointer = fopen("sample.xml", "r"); // Reading XML data from the// specified XML file$xml_data = fread($filePointer, 4096);  // Parsing XML data into an// array structurexml_parse_into_struct($xml_parser,                $xml_data, $values); // Free to xml parsexml_parser_free($xml_parser); // Display array structured XML dataprint_r($values); // Closing the XML filefclose($filePointer); ?>
Output: 
Array
(
    [0] => Array
        (
            [tag] => USER
            [type] => open
            [level] => 1
            [value] => 
        )
    [1] => Array
        (
            [tag] => USERNAME
            [type] => complete
            [level] => 2
            [value] =>  user123 
        )
    [2] => Array
        (
            [tag] => USER
            [value] => 
            [type] => cdata
            [level] => 1
        )
    [3] => Array
        (
            [tag] => NAME
            [type] => complete
            [level] => 2
            [value] =>  firstname lastname 
        )
    [4] => Array
        (
            [tag] => USER
            [value] => 
            [type] => cdata
            [level] => 1
        )
    [5] => Array
        (
            [tag] => PHONE
            [type] => complete
            [level] => 2
            [value] =>  +91-9876543210 
        )
    [6] => Array
        (
            [tag] => USER
            [value] => 
            [type] => cdata
            [level] => 1
        )
    [7] => Array
        (
            [tag] => DETAIL
            [type] => complete
            [level] => 2
            [value] =>  I am John Doe. Live in Kolkata, India. 
        )
    [8] => Array
        (
            [tag] => USER
            [value] => 
            [type] => cdata
            [level] => 1
        )
    [9] => Array
        (
            [tag] => USER
            [type] => close
            [level] => 1
        )
)
geeks.xml file: 
XML
<?xml version="1.0"?><atoms>    <atom>        <name>Carbon</name>        <symbol>C</symbol>        <atomic_no>6</atomic_no>    </atom>    <atom>        <name>Hydrogen</name>        <symbol>H</symbol>        <atomic_no>1</atomic_no>    </atom>    <atom>        <name>Helium</name>        <symbol>He</symbol>        <atomic_no>2</atomic_no>    </atom>    <atom>        <name>Iron</name>        <symbol>Fe</symbol>        <atomic_no>26</atomic_no>    </atom></atoms>
Program 2: 
PHP
<?php  class Atom {    var $name;  // Name of the element    var $symbol;    // Symbol for the atom    var $atomic_no;  // Atomic number         // Constructor for Atom class    function __construct( $aa ) {                 // Initializing or setting the values        // to the field of the Atom class        foreach ($aa as $k=>$v)            $this->$k = $aa[$k];    }}  function read_data($filename) {         // Read the XML database of atoms    $xml_data = implode("", file($filename));         // Creating an xml parser    $xml_parser = xml_parser_create();         xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 0);    xml_parser_set_option($xml_parser, XML_OPTION_SKIP_WHITE, 1);    xml_parse_into_struct($xml_parser, $xml_data, $values, $tags);         // Free to xml parser    xml_parser_free($xml_parser);      // Iterating through the structures    foreach ($tags as $key=>$val) {                 if ($key == "atom") {                         $atom_ranges = $val;                         // Each contiguous pair of array entries            // are the lower and upper range for            // each molecule definition            for($i = 0; $i < count($atom_ranges); $i += 2) {                $offset = $atom_ranges[$i] + 1;                $len = $atom_ranges[$i + 1] - $offset;                                 // Parsing atom data                $tdb[] = parseAtoms(array_slice($values, $offset, $len));            }        }        else {            continue;        }    }    return $tdb;} // parseAtoms function to parse atomfunction parseAtoms($mvalues) {    for ($i = 0; $i < count($mvalues); $i++) {        $ato[$mvalues[$i]["tag"]] = $mvalues[$i]["value"];    }    return new Atom($ato);} $db = read_data("atoms.xml");echo "Database of atoms objects:\n";print_r($db); ?>
Output: 
Database of atoms objects:
Array
(
    [0] => Atom Object
        (
            [name] => Carbon
            [symbol] => C
            [atomic_no] => 6
        )
    [1] => Atom Object
        (
            [name] => Hydrogen
            [symbol] => H
            [atomic_no] => 1
        )
    [2] => Atom Object
        (
            [name] => Helium
            [symbol] => He
            [atomic_no] => 2
        )
    [3] => Atom Object
        (
            [name] => Iron
            [symbol] => Fe
            [atomic_no] => 26
        )
)
Reference: https://www.php.net/manual/en/function.xml-parse-into-struct.php 
anikaseth98
PHP-function
PHP-XML
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
PHP str_replace() Function
How to pass form variables from one page to other page in PHP ?
Create a drop-down list that options fetched from a MySQL database in PHP
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills