Sling Academy
Home/PHP/PHP: How to read and write to an XML file

PHP: How to read and write to an XML file

Last updated: January 11, 2024

Introduction

In today’s data-driven world, XML stands out as a widely-used format for data interchange, and PHP, with its robust set of functions, makes it fairly straightforward to handle XML files. This tutorial will walk you through the process of reading and writing XML files in PHP with practical code examples.

Basic XML Parsing

To begin with XML in PHP, SimpleXML is a convenient choice. This extension provides a simple and easily accessible object model for reading XML. Let’s start by reading an XML file:

<?php
$xml = simplexml_load_file('example.xml');
foreach ($xml->children() as $child) { 
   echo $child->getName() . ': ' . $child . "\n";
}
?>

This code demonstrates how SimpleXML can be used to iterate over child elements of an XML file.

Writing to XML Files

PHP’s DOM extension allows for the creation of XML files. Here’s a basic example:

<?php
$dom = new DOMDocument('1.0', 'UTF-8');
$root = $dom->createElement('root');
$dom->appendChild($root);
$item = $dom->createElement('item', 'content_here');
$root->appendChild($item);
$dom->save('new_example.xml');
?>

This snippet showcases creating a new XML file with DOMDocument and writing content to it.

Advanced XML Manipulation

For more control over XML files, the XMLReader and XMLWriter extensions offer stream-based parsing and writing. This allows for large XML files to be processed without loading them entirely into memory.

<?php
// Reading with XMLReader
$reader = new XMLReader();
$reader->open('example.xml');
while ($reader->read()) {
   if ($reader->nodeType == XMLREADER::ELEMENT && $reader->name == 'item') {
      echo 'Found an <item>: ' . $reader->readInnerXML() . "\n";
   }
}
$reader->close();

// Writing with XMLWriter
$writer = new XMLWriter();
$writer->openURI('new_large_example.xml');
$writer->startDocument('1.0', 'UTF-8');
$writer->startElement('root');
$writer->writeElement('item', 'Big Data Content');
$writer->endElement();
$writer->endDocument();
$writer->flush();
?>

This demonstrates efficient reading and writing, especially beneficial for large XML files with XMLReader and XMLWriter.

Error Handling

It is essential to handle errors when reading and writing XML documents. PHP’s libxml functions can be utilized to catch any XML errors during file operations.

<?php
libxml_use_internal_errors(true);
$xml = simplexml_load_file('invalid.xml');
if ($xml === false) {
   foreach(libxml_get_errors() as $error) {
      echo 'XML Error: ' . $error->message;
   }
}
libxml_clear_errors();
?>

These snippets demonstrate error handling when dealing with XML operations in PHP, ensuring your application can recover gracefully from potential issues.

Conclusion

In this tutorial, we’ve explored the essential techniques for reading and writing to XML files using PHP. Whether for simple data storage or complex data interchange, mastering the manipulation of XML is a powerful tool in a PHP developer’s arsenal. Remember to check your code for errors and choose the appropriate library based on your application’s requirements.

Next Article: PHP: How to download a large file from the internet

Previous Article: PHP: How to calculate total size of a folder (in bytes)

Series: PHP System & FIle I/O Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array