What is XML (Extensible Markup Language)?
Extensible Markup Language, called XML, is used to create documents that are easy to read for both humans and machines. XML is similar to HTML but with significant differences:
- XML is extensible — unlike HTML, which has a fixed set of tags, in XML you can create your own tags (e.g.
<location>,<fullname>). - XML was designed to carry data, not to display it.
- XML tags are self-descriptive — tag names describe the data they enclose.
- An XML parser is used to read and process XML content.
Parsing XML in PHP with simplexml_load_string()
PHP's built-in simplexml_load_string() function converts an XML string into an object you can iterate over. Here is a complete example:
<?php
$xml = "<?xml version='1.0'?>
<newsarticle>
<topic name='Benzine'>
<from>Jennifer</from>
<heading>Actress List</heading>
<body>Details of all actress</body>
</topic>
</newsarticle>";
$xml = simplexml_load_string($xml);
foreach ($xml->topic as $record) {
echo $record['name'], ' ';
echo $record->heading, ' ';
echo $record->body, '<br />';
}
?>
How It Works
simplexml_load_string()parses the XML string and returns aSimpleXMLElementobject.- Child elements are accessed as object properties:
$xml->topic. - Attributes are accessed like array keys:
$record['name']. - The
foreachloop iterates over all<topic>nodes, printing the name attribute, heading, and body.
Hope this tutorial is useful for you. Keep following PHP Tutorial for Beginners for more help.