Current Location: Home> Latest Articles> How to parse XML strings using xml_parse

How to parse XML strings using xml_parse

M66 2025-05-13

In PHP, xml_parse is one of the core functions used to parse XML data. It combines an XML parser ( xml_parser_create ) to parse XML strings and process the parsing results through a callback function. This article will introduce in detail how to use xml_parse to parse XML strings and correctly handle possible situations during parsing.

1. Create an XML parser

In PHP, we first need to create an XML parser instance, which can be implemented using xml_parser_create() :

 <?php
$parser = xml_parser_create();

This $parser variable is the resource handle of the XML parser, and subsequent parsing operations need to be performed based on it.

2. Set the parser's callback function

XML parsing is event-driven, and we need to define callback functions to handle different parts of XML data. For example, we can define how we process it when parsing the start tag, end tag, and character data.

 function startElement($parser, $name, $attrs) {
    echo "Start tag: $name\n";
    if (!empty($attrs)) {
        echo "property:\n";
        foreach ($attrs as $key => $value) {
            echo " - $key: $value\n";
        }
    }
}

function endElement($parser, $name) {
    echo "End tag: $name\n";
}

function characterData($parser, $data) {
    echo "Character data: " . trim($data) . "\n";
}

Then we associate these callback functions to the parser using xml_set_element_handler() and xml_set_character_data_handler() :

 xml_set_element_handler($parser, "startElement", "endElement");
xml_set_character_data_handler($parser, "characterData");

3. Parsing XML data

Now we can parse XML strings using xml_parse() . For example:

 $xmlData = <<<XML
<root>
    <item id="1">The first project</item>
    <item id="2">The second project</item>
</root>
XML;

if (!xml_parse($parser, $xmlData, true)) {
    die(sprintf("XML Parsing error: %s In the process %d",
        xml_error_string(xml_get_error_code($parser)),
        xml_get_current_line_number($parser)
    ));
}

In this example, we define an XML structure and parse it using xml_parse() . If parsing fails, use xml_get_error_code() and xml_error_string() to get the error information and terminate the program.

4. Release parser resources

After using the XML parser, the resource should be released:

 xml_parser_free($parser);

5. Sample output

Assume parsed XML content is as follows:

 <root>
    <item id="1">The first project</item>
    <item id="2">The second project</item>
</root>

After executing the script, the output result is as follows:

 Start tag: ROOT
Start tag: ITEM
property:
 - ID: 1
Character data: The first project
End tag: ITEM
Start tag: ITEM
property:
 - ID: 2
Character data: The second project
End tag: ITEM
End tag: ROOT

6. Handle FAQs in XML parsing

6.1 Illegal XML data encountered

If the XML data parsed by xml_parse() is incorrect, for example:

 <root>
    <item>Unclosed tags
</root>

At this time, xml_parse() will return false and throw a parsing error. You can get the error information through xml_error_string() .

6.2 Handling streaming analysis of large files

If the XML file is large, you can use segmented parsing method:

 $fp = fopen("http://m66.net/example.xml", "r");
while ($data = fread($fp, 4096)) {
    if (!xml_parse($parser, $data, feof($fp))) {
        die(sprintf("XML Parsing error: %s In the process %d",
            xml_error_string(xml_get_error_code($parser)),
            xml_get_current_line_number($parser)
        ));
    }
}
fclose($fp);

This can avoid memory overflow issues caused by loading the entire XML file at once.

7. Conclusion

Using xml_parse to parse XML data in PHP is an efficient method, but the callback function needs to be set correctly to handle different parsing events. In addition, handling XML parsing errors and large file parsing is the key to improving program robustness. I hope this article can help you better understand and apply PHP's XML parsing function!