PHP and XML


XML stands for eXtensible Markup Language which serves to store and transmit data in a structured way that humans can easily read. The XML language finds extensive application in configuration files and RSS feeds as well as web services such as SOAP.

php-and-xml

How PHP Works with XML

Method Description
SimpleXML Easy-to-use and beginner-friendly
DOMDocument More powerful, supports XML manipulation
XMLReader Streaming parser, memory efficient

Reading XML with SimpleXML

<users>
    <user>
        <name>Alice</name>
        <email>alice@example.com</email>
    </user>
    <user>
        <name>Bob</name>
        <email>bob@example.com</email>
    </user>
</users>
 

PHP Code:

<?php
$xml = simplexml_load_file("data.xml");

foreach ($xml->user as $user) {
    echo "Name: " . $user->name . "<br>";
    echo "Email: " . $user->email . "<br><br>";
}
?> 

Reading XML from a String

$xmlString = <<<XML
<book>
  <title>PHP Basics</title>
  <author>John Doe</author>
</book>
XML;

$xml = simplexml_load_string($xmlString);
echo $xml->title;  // Output: PHP Basics 

Creating XML with SimpleXMLElement

$xml = new SimpleXMLElement("<users></users>");
$user = $xml->addChild("user");
$user->addChild("name", "Charlie");
$user->addChild("email", "charlie@example.com");

Header('Content-type: text/xml');
echo $xml->asXML(); 



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.