0

Could someone please provide the simplest/shortest code that can edit the values within an xml node? I have been searching this for hours and all that I get are errors and failures. I need something that can get the node (/node/node1/node2) and edit the contents within it. I am using php-5. Thanks

Edit: Lets say I have this xml file:

<node>
  <node2>
    Content
  </node2>
</node>

What I need to do is change the value of <node2> from "content" to something else.

hakre
  • 193,403
  • 52
  • 435
  • 836
Preston
  • 1,039
  • 3
  • 12
  • 22
  • possible duplicate of [A simple program to CRUD node and node values of xml file](http://stackoverflow.com/questions/4906073/a-simple-program-to-crud-node-and-node-values-of-xml-file) – Gordon Feb 18 '11 at 07:46

2 Answers2

3

SimpleXML

$doc = simplexml_load_file('http://example.com/example.xml');

// Note the SimpleXMLElement is the root node, ie <node>
$doc->node2 = 'new content';

$doc->asXml('new-filename.xml'); // Note, saves locally
// or
$xmlString = $doc->asXml();
Phil
  • 157,677
  • 23
  • 242
  • 245
  • What would I need to add if the xml is a remote file? – Preston Feb 18 '11 at 01:54
  • @Phil Brown It is adding new nodes, not updating the current ones. Is there any other code you can provide? thanks – Preston Feb 18 '11 at 02:27
  • @Preston I don't think you can add new nodes using that method. Always thought you had to use `SimpleXMLElement::addChild()`. In any case, it would probably be very specific to the document structure. Perhaps you could add an example to your question. – Phil Feb 18 '11 at 02:33
  • 1
    @Preston Edited my answer accordingly – Phil Feb 18 '11 at 02:41
  • @Phil Brown For some reason, it is still adding another tag at the end of the file and keeping the other part also. Any other suggestions/code? – Preston Feb 18 '11 at 02:49
  • 1
    @Preston Are there any other `` nodes? If so, you need to identify which one to modify by its index, eg `$doc->node2[0] = 'new content';` – Phil Feb 18 '11 at 02:51
  • @Phil Brown Thank you for the help. I finally got it by doing this: $doc->node->node2[0] = 'new content'; – Preston Feb 18 '11 at 03:11
0

You are looking for SimpleXML, great class for XML parsing/editing

Stoosh
  • 2,408
  • 2
  • 18
  • 24