Parse XML data into an array in PHP

Description

The following code shows how to parse XML data into an array.

Example


<?php/*from  w w w. jav  a  2  s . c  o m*/
    //invalid xml file
    $xmlfile = 'test.xml';
    $xmlparser = xml_parser_create();

    // open a 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);
?>

The following code is for test.xml.


//w  w w  .j  a  v  a 2s  .co  m
    <?xml version="1.0" encoding="UTF-8"?>
    <note>
    <to>Work</to>
    <from>Home</from>
    <heading>Reminder</heading>
    <body>This is a message.</body>
    </note>

The code above generates the following result.





















Home »
  PHP Tutorial »
    XML »




DOM
SimpleXML
SimpleXMLElement
XML Parser