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
  • 173
  • 1
  • 6
Oliver Bayes-Shelton
  • 6,135
  • 11
  • 52
  • 88
  • Possible duplicate of [How can I set text value of SimpleXmlElement without using its parent?](http://stackoverflow.com/questions/3153477/how-can-i-set-text-value-of-simplexmlelement-without-using-its-parent) – Stephan Weinhold Jan 25 '17 at 10:02

4 Answers4

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.

cletus
  • 616,129
  • 168
  • 910
  • 942
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' );
Jan Hančič
  • 53,269
  • 16
  • 95
  • 99
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.

ctrygstad
  • 131
  • 1
  • 3
  • 11
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!

CSepulveda
  • 11
  • 1