How to edit or replace xml string using php?

4.1k views Asked by At

I had to change my question to simple question

For example: my XML file name is: ABC.xml

inside of this xml file is:

<li class="thumb"><a class="Alibaba" href="google.com"></a></li>

So, here is my question: How to use PHP to search string inside of ABC.xml and find Alibaba name and replace it to AlibabaColor name and save it to ABC.xml

Please guide me and give me an example for this. Thank you

1

There are 1 answers

2
Jesse On

You can do this using php str_replace among many other functions. Here is a couple examples ->

If the XML is in a string already you can do this

PHP:

<?php
    $myXmlString = str_replace('Alibaba', 'AlibabaColor', $myXmlString);
?>

If you need to get the XML data from another file there are a few ways to to do it depending on if you need to save it, just replace it and display it, or really what you are doing. Some of this comes down to preference.

Just need to display it?

<?php
    $xml = file_get_contents(/path/to/file); // or http://path.to/file.xml
    $myXmlString = str_replace('Alibaba', 'AlibabaColor', $xml);
?>

Need to change the file itself?

<?php
    $xml = file_get_contents(/path/to/file); // or http://path.to/file.xml
    $myXmlString = str_replace('Alibaba', 'AlibabaColor', $xml);
    file_put_contents(/path/to/file, $myXmlString);
?>

--

To answer the below comment, here is working code from my server ->

xml:

<li>hello</li>

php:

$file = '/home/username/public_html/xml.xml';
$xml = file_get_contents($file);
$text = str_replace('hello','world',$xml);
file_put_contents($file, $text);

xml.xml after:

<li>world</li>

Keep in mind to change 'username' to the right one, or use an FQDN if you are more comfortable doing so. Make sure that the file has permission to be written to by a script as well.