11

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 existing file ?

srb
1731 silver badge6 bronze badges
asked Jan 19, 2010 at 8:42
1

4 Answers 4

14

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.

answered Jan 19, 2010 at 8:49
Sign up to request clarification or add additional context in comments.

Comments

7

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' );
answered Jan 19, 2010 at 8:48

Comments

4

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.

answered Nov 11, 2010 at 16:34

Comments

1

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"/>&lt;b&gt;Text. This supports html code.&lt;/b&gt;&lt;br/&gt;I also work with variables, like GET or POST.</ANode>
 </Texts>
</sitedata>

Hope it helps!

answered Aug 18, 2017 at 17:30

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.