Home >Backend Development >PHP Tutorial >How do you parse and process HTML/XML in PHP?
This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage and exchange between applications. PHP's simplexml_load_string()
function simplifies XML string parsing, converting the input into a readily accessible object.
simplexml_load_string()
FunctionThe simplexml_load_string()
function takes an XML string as input and returns a SimpleXMLElement
object. This object provides properties and methods for convenient XML data access.
The following code snippet illustrates this process. It parses a sample XML string and displays its structure using print_r()
.
<code class="language-php"><?php $xmlString = "<?xml version='1.0' encoding='UTF-8'??><note><to>Tutorial Points</to><from>Pankaj Bind</from><heading>Submission</heading>Welcome to Tutorials Points</note>"; $xmlObject = simplexml_load_string($xmlString); if (!$xmlObject) { die("Error: Unable to create XML object."); } print_r($xmlObject); ?></code>
<code>SimpleXMLElement Object ( [to] => Tutorial Points [from] => Pankaj Bind [heading] => Submission [body] => Welcome to Tutorials Points )</code>
The output shows a SimpleXMLElement
object representing the parsed XML string. print_r()
effectively visualizes the object's structure and its corresponding XML elements.
This example demonstrates accessing specific XML node values within the SimpleXMLElement
object.
<code class="language-php"><h2>Tutorial Points</h2> <b>Accessing XML Data</b><br><br> <?php $xmlString = "<?xml version='1.0' encoding='UTF-8'??><note><to>Tutorial Points</to><from>Pankaj</from><heading>Submission</heading>Welcome to Tutorials Points</note>"; $xmlObject = simplexml_load_string($xmlString); if (!$xmlObject) { die("Error: Unable to create XML object."); } echo "To: " . $xmlObject->to . "<br>"; echo "From: " . $xmlObject->from . "<br>"; echo "Subject: " . $xmlObject->heading . "<br>"; echo "Message: " . $xmlObject->body; ?></code>
This clearly shows how to directly access and display individual node values from the parsed XML data.
The above is the detailed content of How do you parse and process HTML/XML in PHP?. For more information, please follow other related articles on the PHP Chinese website!