PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
112: DOMDocument for XML Manipulation
I’ve seen a lot of developers treat XML like it's just a weirdly formatted string. When you're in a rush to update a single value in a configuration file or an API response, the temptation to just use str_replace() or a clever regular expression is incredibly strong. It feels faster. You don't have to learn a new API; you just hunt for the tag and swap the value. But if you've ever had a regex accidentally wipe out half your document because of a nested tag or a stray attribute, you know exactly why that's a disaster waiting to happen.
Let's look at a real-world scenario: you're managing a product feed for an e-commerce site. You have an XML file with hundreds of products, and you need to find a specific product by its ID and update its price, while also adding a status="on_sale" attribute to that product node. Here is how the "quick and dirty" approach usually looks:
<?php
$xml = file_get_contents('products.xml');
// This is the "danger zone"
$xml = preg_replace('/().*?().*?(.*?)(\<\/price>)/s', '$1$2 19.99$4', $xml);
file_put_contents('products.xml', $xml);
?>
The fragility of string manipulation
The problem here isn't just that the regex is hard to read—it's that XML isn't a regular language. If a colleague decides to add a currency="USD" attribute to the price tag, your regex breaks. If there's a comment inside the product node, your regex might capture too much. You're treating a structured tree as if it's a flat line of text, and in production, that's how you end up with corrupted data feeds that crash your partner's import scripts.
The better way is to use DOMDocument. It parses the XML into a tree structure in memory. Instead of "searching for text," you're "navigating a hierarchy." It's more verbose, yes, but it's surgically precise.
<?php
$doc = new DOMDocument();
$doc->load('products.xml');
// Use XPath to find the exact node regardless of where it sits in the tree
$xpath = new DOMXPath($doc);
$product = $xpath->query("//product[@id='123']")->item(0);
if ($product) {
// Update the price child node
$priceNode = $product->getElementsByTagName('price')->item(0);
$priceNode->nodeValue = '19.99';
// Add the sale attribute safely
$product->setAttribute('status', 'on_sale');
}
$doc->save('products.xml');
?>
Paying the "verbosity tax" for reliability
If you compare the two, the DOMDocument approach takes significantly more lines of code. You have to instantiate the document, create an XPath object, and carefully traverse the nodes. I call this the "verbosity tax." You're paying more in typing time to get a guarantee that you won't accidentally delete a closing tag or break the encoding of your file.
One thing that trips people up is that DOMDocument is very strict. If your XML is slightly malformed, load() will throw warnings. I usually recommend using libxml_use_internal_errors(true) before loading the file so you can handle those errors gracefully in your own logs rather than letting PHP dump them all over your output. It's a small detail, but it's the difference between a script that "just works" and one that's actually production-ready.
When you're just reading a simple XML file, SimpleXML is often enough. But the moment you need to modify attributes, handle complex namespaces, or perform surgical updates to a large document without risking the structural integrity of the file, DOMDocument is the only tool you should be reaching for.
📋 Practical Task
Exercise: Synchronizing a Vendor Inventory Feed
You have been provided with an XML file named inventory.xml containing a list of warehouse items. Each item has an sku attribute and a quantity child element.
Write a PHP script that performs the following operations using DOMDocument and DOMXPath:
- Locate the item with
sku="WH-502". - Change its
quantityfrom its current value to0. - Add a new attribute to the product tag:
availability="out_of_stock". - Find all items with a
quantityof0and add a child element<restock_date>2023-12-01</restock_date>to each of those items. - Save the modified XML back to the file.
Make sure your script handles the case where the SKU "WH-502" might not exist in the file to avoid calling methods on null.
There are no comments for now.