How can I edit the value's in a xml file using simpleXML ?
I know how to create the file, but not how to edit the value in an existin开发者_运维技巧g file ?
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.
Load your XML with SimpleXML and make the changes. Then you can use the asXML method to save the XML to a file (you pass the filename as the argument):
$xml = new SimpleXMLElement( $xmlString );
// do the manipulation here
$xml->asXML ( '/path/to/your/file.xml' );
Keep in mind that although you can edit XML with SimpleXML, there are limitations. For example, you can remove or delete a node or element. You can clear it so that its blank, but you can't eliminate it altogether. For that, you need DOM, or something like that.
I am working like this (it's quite the same but it could help): The file test.xml could be any extension as long as it's a plain xml text.
test.xml:
<?xml version="1.0" encoding="utf-8"?>
<sitedata>
<Texts>
<ANode SomeAttr="Green" OtherAttr="Small"/>This is the text I'm changing.</ANode>
</Texts>
</sitedata>
And the PHP code:
$xml=simplexml_load_file("test.xml") or die("Error: Cannot create object");
$SomeVar="<b>Text. This supports html code.</b><br/>I also work with variables, like GET or POST.";
$xml->Texts[0]->{'ANode'}=$SomeVar;
$xml->asXml('test.xml');
Results test.xml:
<?xml version="1.0" encoding="utf-8"?>
<sitedata>
<Texts>
<ANode SomeAttr="Green" OtherAttr="Small"/><b>Text. This supports html code.</b><br/>I also work with variables, like GET or POST.</ANode>
</Texts>
</sitedata>
Hope it helps!
精彩评论