Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

edit XML with simpleXML

Tags:

php

xml

simplexml

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 ?

like image 694
Oliver Bayes-Shelton Avatar asked Jan 19 '10 08:01

Oliver Bayes-Shelton


People also ask

How we can change a value of XML document with simple XML?

The way to change the value of an attribute, is to change its text value. This can be done using the setAttribute() method or setting the nodeValue property of the attribute node.

What is SimpleXML extension?

SimpleXML is an extension that allows us to easily manipulate and get XML data. SimpleXML provides an easy way of getting an element's name, attributes and textual content if you know the XML document's structure or layout.

How do I create a SimpleXML object?

Example #2 Create a SimpleXMLElement object from a URL$sxe = new SimpleXMLElement('http://example.org/document.xml', NULL, TRUE); echo $sxe->asXML();


1 Answers

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!

like image 139
CSepulveda Avatar answered Oct 19 '22 16:10

CSepulveda