Jump to content

PHP5 - Edit xml document using DOM XML


Mr Candu

Recommended Posts

Hi,

My xml document "visitors.xml" has the following layout:

<?xml version="1.0" ?>

<visitors>

  <visitor id="1">

    <name>John Smith</name>

    <site>1</site>

  </visitor>

  <visitor id="2">

    <name>Mrs Golubovic</name>

    <site>1</site>

  </visitor>

</visitors>

I would like to do the following 2 things with PHP5 preferably using DOM XML, though if xpath and/or simplexml is better suited that would be fine also.

 

1) Open the xml file and change the name of the visitor with an attribute id of 1, from John Smith to Jane Smith, then save the file.

 

2) Open the xml file an add a new visitor record with an attribute id of 3, name of Rob Jones and site of 1, then save the file.

 

Any help and advice you might be able to give me would be great.

Thanks in advance,

Mat.

Link to comment
https://forums.phpfreaks.com/topic/134981-php5-edit-xml-document-using-dom-xml/
Share on other sites

<?php
  $file = 'visitors.xml';
  
  $xml = simplexml_load_file($file);
  list($node) = $xml->xpath('/visitors/visitor[@id=1]');
  $node->name = 'Jane Smith';
  $xml->asXML($file);
  
  $xml = simplexml_load_file($file);
  $visitor = $xml->addChild('visitor');
  $visitor->addAttribute('id','3');
  $visitor->addChild('name','Rob Jones');
  $visitor->addChild('site','1');
  $xml->asXML($file);
?>

<?php
  $file = 'visitors.xml';
  
  $xml = simplexml_load_file($file);
  list($node) = $xml->xpath('/visitors/visitor[@id=1]');
  $node->name = 'Jane Smith';
  $xml->asXML($file);
  
  $xml = simplexml_load_file($file);
  $visitor = $xml->addChild('visitor');
  $visitor->addAttribute('id','3');
  $visitor->addChild('name','Rob Jones');
  $visitor->addChild('site','1');
  $xml->asXML($file);
?>

 

Perfect! Thanks very much.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.