edit XML with simpleXML
Sure you can edit with SimpleXML:
$input = <<<END
<?xml version='1.0' standalone='yes'?>
<documents>
<document>
<name>spec.doc</name>
</document>
</documents>
END;
$xml = new SimpleXMLElement($input);
$xml->document[0]->name = 'spec.pdf';
$output = $xml->asXML();
Take a look at the examples.
trying to edit xml file using php simplexml
Second one is not possible as SimpleXMLElement
can only take a well-formed XML string or the path or URL to an XML document. But you are passing an object of class SimpleXMLElement
returned by simplexml_load_file
. That is the reason it was throwing error String couldn't be parsed to XML...
In first one the asXML()
method accepts an optional filename as parameter that will save the current structure as XML to a file.
If the filename isn't specified, this function returns a string on
success andFALSE
on error. If the parameter is specified, it
returnsTRUE
if the file was written successfully andFALSE
otherwise.
So once you have updated your XML with the hints, just save it back to file.
$settings = simplexml_load_file("settings.xml");
....
if(isset($aInformation['cName']))
{
$settings->general->communityname = $aInformation['cName'];
// Saving the whole modified XML to a new filename
$settings->asXml('updated_settings.xml');
// Save only the modified node
$settings->general->communityname->asXml('settings.xml');
}
Editing XML Nodes through SimpleXML PHP
Get the server object/array where $serverName = "Google"
// An array of all <server> elements with the chosen name
$googles = $servers->xpath('server[name = " Google "]');Edit the server's address field to something different like http://www.google.co.uk
//Find a google and change its address
$google->address = 'http://www.google.co.uk';Write the changes back to the XML file.
$servers->saveXML('path/to/file.xml');
Full example
$servers = simplexml_load_file('path/to/file.xml');
$googles = $servers->xpath('server[name=" Google "]');
foreach ($googles as $google) {
$google->address = 'http://www.google.co.uk';
}
$servers->saveXML('path/to/file.xml');
More info
- SimpleXML Basic Usage
- XPath tutorial
Updating a xml file with php simplexml tool
You need to save modified xml back into file
<?php
$completeurl = $_SERVER['DOCUMENT_ROOT'].'/ytplayer/videolar.xml';
$xml = simplexml_load_file($completeurl);
$xml->track[0]->title = 'Whitesnake - Is this love';
$xml->track[0]->youtube = 'GOJk0HW_hJw';
$xml->asXML($completeurl)
?>
How do I edit an XML file in SimpleXML, based on the contents of the XML, if there are multiple values of the same tag?
You can achieve this just with SimpleXML
- you don't need to involve DOMDocument
at all.
The xpath
method returns the <user>
element you're looking for. You can then modify it simply by updating the password property (or add new ones, or attributes, etc). This updates the underlying SimpleXMLElement
object, which you can then write back to the file as a string using asXML
.
$filename = 'file.xml';
$sxml = simplexml_load_file($filename);
$username = "desbest";
$user = $sxml->xpath("./user[./username = '{$username}']")[0];
$user->password = 'testpassCHANGED';
file_put_contents($filename, $sxml->asXML());
See https://eval.in/923654 for an example
PHP Recursively Edit XML Document with Simplexml
You are most likely looking for something that I worded SimpleXML-Self-Reference once. It does work here, too.
And yes, Simplexml has support for SPL and RecursiveIteratorIterator
.
So first of all, you can directly make $xml
work with tree-traversal by opening the original XML that way:
$buffer = <<<BUFFER
<sample>
<example>
<name>David</name>
<age>21</age>
</example>
</sample>
BUFFER;
$xml = simplexml_load_string($buffer, 'SimpleXMLIterator');
// #################
That allows you to do all the standard modifications (as SimpleXMLIterator
is as well a SimpleXMLElement
) but also the recursive tree-traversal to modify each leaf-node:
$iterator = new RecursiveIteratorIterator($xml);
foreach ($iterator as $node) {
$node[0] = strtoupper($node);
// ###
}
This exemplary recursive iteration over all leaf-nodes shows how to set the self-reference, the key here is to assign to $node[0]
as outlined in the above link.
So all left is to output:
$xml->asXML('php://output');
Which then simply gives:
<?xml version="1.0"?>
<sample>
<example>
<name>DAVID</name>
<age>21</age>
</example>
</sample>
And that's the whole example and it should also answer your question.
Edit XML with CDATA using SimpleXMLElement
The XML written out contains no CDATA nodes, because you told SimpleXML to get rid of them when you passed LIBXML_NOCDATA
. To keep them, simply don't pass that option!
Here's a live demo of the fixed version, as below:
<?php
$str_xml = "<myxml><mytag><![CDATA[In this content, 8 > 2 & 1 < 9, and 10 is a 10% of 100. ]]></mytag></myxml>";
try {
echo "XML with CDATA: \n\n";
$xml = simplexml_load_string($str_xml);
echo $xml->asXML() ."\n\n";
} catch(Exception $e){
echo "XML with CDATA: \n\n";
echo $e->getMessage() ."\n\n";
}
All the answers and comments you have read telling you you need to pass that option in order to use CDATA nodes with SimpleXML are quite simply wrong. The only problem is that the output of print_r
, var_dump
, etc, doesn't give a full representation of the data accessible by SimpleXML; that doesn't mean it's not there.
To get at the text in your example XML, you just need to cast the element to string (some contexts, such as an echo
statement, do this automatically). As in this example:
$xml = simplexml_load_string($str_xml);
$tag_content = (string)$xml->mytag;
echo "Here is the content of the <mytag> node: $tag_content";
How to modify a XML node by attribute
When you use XPath as you say it returns an array. As this is the first item you want to change you use [0]
.
To update the value, you have to get SimpleXML to know you want to set the value of the element, the simplest way of doing this is to use (in this case) is $foo[0]
. Although $foo
isn't an array, it fools SimpleXML into setting the value of the element rather than assigning a value to the variable called $foo
.
$xmlStr = '<?xml version="1.0" encoding="utf-8"?>
<players>
<string name="Paul">Foo</string>
<string name="Peter">Bar</string>
</players>';
$xml = new SimpleXMLElement($xmlStr);
$foo = $xml->xpath('//string[@name="Paul"]')[0];
$foo[0] = 'Baobab';
echo $xml->asXML();
If you knew this was always going to be the layout of the XML, you could just do...
$xml->string[0] = 'Baobab';
Related Topics
PHP Try-Catch Blocks: Are They Able to Catch Invalid Arg Types
PHP Warning: Exec() Unable to Fork
How to Select Multiple Rows from MySQL with One Query and Use Them in PHP
PHP Run Once and Insert Twice in MySQL Database
Get the Hierarchy of a Directory with PHP
Using Fetch_Assoc on Prepared Statements
Mod_Rewrite, PHP and the .Htaccess File
How to Install Composer on App Service
Disable Add to Cart Button for an Array of Products Ids in Woocommerce
How to Pass Multiple Variables Across Multiple Pages
PHP Sample Script for Pagination
Array_Map Function in PHP with Parameter
Foreach Value from Post from Form