To search and replace tag values in XML files using PHP, we use the PHP string replace function str_replace()
. This is a PHP built-in function which majorly used to replace a specific string with another string.
Here PHP str_replace Function | Complete Guide you can learn a complete guide with different examples.
Complete Code to Search and Replace Tag Values in XML File using PHP
1 2 3 4 5 6 7 |
<?php $xml = file_get_contents("https://www.w3schools.com/xml/note.xml"); echo "<b>Original Text:</b>".$xml."<br/>"; $myXmlString = str_replace('Tove', 'John Doe', $xml); echo "<b>Replace Text:</b>".$myXmlString; ?> |
Output:
Original Text: Tove Jani Reminder Don’t forget me this weekend!
Replace Text: John Doe Jani Reminder Don’t forget me this weekend!
Code Highlights:
In the above example, we get the XML file data by using file_get_contents()
, that is a PHP built-in function. To know more about you can check here PHP file_get_contents() Function With Example.
This function is used to read complete file data and print.
After fetching complete data we use str_replace()
the function to replace the first word of the statement.
Then we print both the original string and replaced string.
Search and Replace XML Tag in PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php $XML = '<note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Do not forget me this weekend!</body> </note>'; $XML = str_replace('to', 'toName', $XML); $XML = str_replace('from', 'fromName', $XML); $XML = str_replace('<', '<', $XML); echo '<pre>' . $XML . '</pre>'; ?> |
Output:
Code Highlights:
In the above example, first, define a variable with an XML tag and its value.
By using PHP str_replace() function we replace XML tags and print the output.
Conclusion
Here we discuss, how we can Search and Replace Tag values in XML Files using PHP with the help of an example.
You can run it using our online compiler https://codingtasks.net/php-online-editor/.
I hope you all understand the complete code.
Please let me know if you are facing any issues at the time of implementation.
To know more about PHP XML you can check here PHP: XML Parser – Manual.
Happy Coding..!