Tuesday, October 7, 2025
HomeLanguagesHow to parse and process HTML/XML using PHP ?

How to parse and process HTML/XML using PHP ?

In this article, we will learn how to process XML using PHP. We have already learnt the basics of XML and their differences with respect to HTML. Different elements of XML can be learnt from XML Elements to understand the working of the following programs.

The simplexml_load_string() function is used to parse the given XML and then the XML object can be used for accessing the XML data.

Example 1: The following example reads and prints the given XML string.

HTML




<html>
 
<body>
    <?php
    /* XML string */
    $myXMLData =
    "<?xml version='1.0' encoding='UTF-8'?>
    <note>
        <to>GeeksForGeeks</to>
        <from>Tom</from>
        <heading>Submission</heading>
 
        <body>
            Please see my articles of PHP!
        </body>
    </note>";
 
    /* The function reads xml data
       from the passed string */
    $xml = simplexml_load_string($myXMLData)
    or die("Error: Cannot create xml data object");
     
    print_r($xml);
    ?>
</body>
 
</html>


Output:

 SimpleXMLElement Object
 (
    [to] => GeeksForGeeks
    [from] => Tom
    [heading] => Submission
    [body] => Please see my articles of PHP!
 )

Example 2: The following example demonstrates how to get XML node values using PHP. The node values are shown in the output given below.

HTML




<!DOCTYPE html>
<html>
 
<body>
    <h2>GeeksForGeeks </h2>
    <b>
        Get data from XML data string
    </b>
     
    <br /><br />
    <?php
    // XML string
    $myXMLData =
        "<?xml version='1.0' encoding='UTF-8'?>
     
    <note>
        <to>GeeksForGeeks</to>
        <from>John</from>
        <heading>Submission</heading>
 
        <body>Please see my articles of PHP!</body>
    </note>";
 
    /* The function reads xml data
       from the passed string */
    $xml = simplexml_load_string($myXMLData)
    or die("Error: Cannot create xml data object");
    echo "To : " . $xml->to . "<br>";
    echo "From : " . $xml->from . "<br>";
    echo "Subject : " . $xml->heading . "<br>";
    echo "Mail : " . $xml->body;
    ?>
</body>
 
</html>


Output:

 

RELATED ARTICLES

Most Popular

Dominic
32340 POSTS0 COMMENTS
Milvus
86 POSTS0 COMMENTS
Nango Kala
6708 POSTS0 COMMENTS
Nicole Veronica
11872 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11936 POSTS0 COMMENTS
Shaida Kate Naidoo
6829 POSTS0 COMMENTS
Ted Musemwa
7090 POSTS0 COMMENTS
Thapelo Manthata
6780 POSTS0 COMMENTS
Umr Jansen
6784 POSTS0 COMMENTS