How to modify xml file using PHP

How to modify xml file using PHP

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

How to Modify XML Files Using PHP for Dynamic Data Management

Managing XML files that act as persistent storage for search results presents a unique set of challenges, particularly when the data structure needs to evolve based on user queries. The specific requirement you described involves maintaining a single XML file where elements are appended upon discovery and removed if re-queried with the same type. This pattern effectively treats the XML file as a cache that must be deduplicated or refreshed based on state.

The core logic here is a conditional append strategy: check for existing data matching the query type, remove it if present, then append new results. To achieve this in PHP, you cannot rely solely on string manipulation functions like str_replace or regex. While tempting for simple files, these methods break easily with nested structures and special characters found in addresses or titles. Instead, you should parse the document into a tree structure to ensure data integrity.

Parsing and Conditional Logic

The standard approach involves using PHP's built-in DOM extension. First, load the XML file into a DOMDocument object. This gives you access to the node hierarchy without risking corruption of tags or attributes.

$dom = new DOMDocument();
// Suppress warnings for malformed initial files if necessary
libxml_use_internal_errors(true); 
if ($dom->load('markers.xml')) {
    libxml_clear_errors();
} else {
    // Handle loading errors appropriately
    exit("Failed to load XML file.");
}

Once loaded, the script must navigate the DOM tree. You need to query for existing <marker> elements where the <type> child matches your search term (e.g., "hotels"). The logic follows a specific sequence: locate the node, remove it from its parent, and then create a fresh instance with the new data before saving.

Implementing the Search and Update Cycle

Here is how you implement the removal and appending logic. This code assumes you have an array of new search results ready to be inserted as child nodes.

$searchType = 'hotels'; 

// 1. Remove existing markers of the same type
$markersNode = $dom->getElementsByTagName('markers')->item(0);
if ($markersNode) {
    $existingMarkers = $markersNode->getElementsByTagName('marker');
    
    foreach ($existingMarkers as $marker) {
        $typeNode = $marker->getElementsByTagName('type')->item(0);
        
        if ($typeNode && trim($typeNode->nodeValue) === $searchType) {
            $marker->parentNode->removeChild($marker);
        }
    }
}

// 2. Append new markers (example for a single result)
$newMarker = $dom->createElement('marker');
$newType = $dom->createElement('type', $searchType);
$newTitle = $dom->createElement('title', 'New Hotel Found');
$newAddress = $dom->createElement('address', '123 Main St');
$newLat = $dom->createElement('latitude', '40.7128');
$newLng = $dom->createElement('longitude', '-74.0060');

$newMarker->appendChild($newType);
$newMarker->appendChild($newTitle);
$newMarker->appendChild($newAddress);
$newMarker->appendChild($newLat);
$newMarker->appendChild($newLng);

$markersNode->appendChild($newMarker);

This approach ensures that the file state reflects exactly what is currently requested. If a user searches for "schools" after "hotels," you repeat this process with the new type string. The previous "hotels" data remains untouched because the condition trim($typeNode->nodeValue) === $searchType fails, and only the new schools are appended.

Handling Encoding and Save Mechanics

A critical detail often overlooked is the XML declaration at the top of your file. Your source material specifies encoding="ISO-8859-1". PHP's DOM extension defaults to UTF-8. If you load an ISO-8859-1 file and save it without specifying the encoding, the resulting file will be converted to UTF-8 by default, potentially breaking legacy systems expecting the original character set.

To preserve the declaration, you must explicitly set the document encoding before saving:

$dom->saveXML($dom, 'markers.xml', [
    'indent' => true,
    'encoding' => 'ISO-8859-1' // Match your original file
]);

Trade-offs and Considerations

While this method works well for small to medium datasets, storing search results in a flat XML file introduces significant performance bottlenecks as the file grows. Parsing large XML documents is computationally expensive compared to querying a database index. Furthermore, concurrent writes from multiple users can lead to race conditions where data gets overwritten or corrupted during the load and save cycle.

For production environments handling frequent updates, consider moving this logic to a relational database or using an in-memory cache like Redis for the search results, writing to XML only for export tasks. However, if you are constrained to file-based storage, this DOM-based pattern provides a robust way to maintain state without manual file editing.

Our network