Search code examples
phpxmlsimplexml

Replace text in xml loaded with simplexml_load_file()?


I have this xml file:

<flats>
    <flat>

        <images1>http://www.example.com/image1.jpg</images1>
        <images2>http://www.example.com/image1.jpg</images2>

    </flat>
</flats>

Which I need to load using php and then replace some node names to get this (just change image1 and image2 to images:

<flats>
    <flat>

        <images>http://www.example.com/image1.jpg</images>
        <images>http://www.example.com/image1.jpg</images>

    </flat>
</flats>

I managed to load and save the file, but I don't know how to replace the node names.

$xml_external_path = 'http://external-site.com/original.xml';
$xml = simplexml_load_file($xml_external_path);

$xml->asXml('updated.xml');

UPDATE: PHP

    $xml_external_path = 'http://external-site.com/original.xml';
    $xml = simplexml_load_file($xml_external_path);
    print_r($xml);
    $newXml = str_replace( 'images1', 'image',$xml ) ;
    print_r($newXml);

Solution

  • If you want to just rename the <images1> and <images2> tags I suggest you go with the simplest solution, i.e. text replace using str_replace.

    $xml_external_path = 'http://external-site.com/original.xml';
    $xml = simplexml_load_file($xml_external_path);
    
    $searches = ['<images1>', '<images2>', '</images1>', '</images2>'];
    $replacements = ['<images>', '<images>', '</images>', '</images>'];
    
    $newXml = simplexml_load_string( str_replace( $searches, $replacements, $xml->asXml() ) );
    $newXml->asXml('updated.xml');
    

    If you however need a more sophisticated way to handle the task you may want to take a look at the DOMDocument class and build your own new XML