Parse and Process HTML & XML in PHP



This article explains how to handle XML documents in PHP. XML (eXtensible Markup Language) is defined as a textual markup language designed for both people and computers. It is a format used for storing and moving data between applications. PHP simplexml_load_string() function provided by PHP allows us to parse XML strings with ease and this function will convert XML string into an object for us which can be examined in order to understand XML data.

Usong PHP simplexml_load_string() Method

PHP simplexml_load_string() function accepts an XML string and returns a SimpleXMLElement object, the object has properties and methods that will allow the user to access XML.

Parsing XML and Displaying as an Object

The code below does exactly the same, it reads the given provided XML string and prints out its structure with print_r().

Example Code

<!DOCTYPE html>
<html>
<body>
    <?php
    /* XML string */
    $myXMLData = "<?xml version='1.0' encoding='UTF-8'?>
    <note>
        <to>Tutorial Points</to>
        <from>Pankaj Bind</from>
        <heading>Submission</heading>
        <body>Welcome to Tutorials Points</body>
    </note>";

    /* Parse the XML string */
    $xml = simplexml_load_string($myXMLData)
    or die("Error: Cannot create XML data object");

    /* Print the parsed XML as an object */
    print_r($xml);
    ?>
</body>
</html>

Output

SimpleXMLElement Object
(
    [to] => Tutorial Points 
    [from] => Pankaj Bind
    [heading] => Submission
    [body] => Welcome to Tutorials Points 
)

In this case, a SimpleXMLElement object has been created containing an XML string. print_r function has been used to display the object structure and elements of XML that the object represents.

Accessing XML Node Values

In this example, we use these methods that allow us to access certain XML node values that have been stored in a SimpleXMLElement object.

<!DOCTYPE html>
<html>
<body>
    <h2>Tutorial Points</h2>
    <b>Retrieve data from XML</b><br/><br/>
    
    <?php
    /* XML string */
    $myXMLData = "<?xml version='1.0' encoding='UTF-8'?>
    <note>
        <to>Tutorial Points</to>
        <from>Pankaj</from>
        <heading>Submission</heading>
        <body>Welcome to Tutorials Points</body>
    </note>";

    /* Parse the XML string */
    $xml = simplexml_load_string($myXMLData)
    or die("Error: Cannot create XML data object");

    /* Display XML node values */
    echo "To : " . $xml->to . "<br>";
    echo "From : " . $xml->from . "<br>";
    echo "Subject : " . $xml->heading . "<br>";
    echo "Message : " . $xml->body;
    ?>
</body>
</html>

Output


Updated on: 2024-11-11T11:23:10+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements