How to edit data in XML file with php ?

Discussion in 'PHP' started by Shimurai, Jun 24, 2011.

  1. #1
    Hi guys,

    I'm trying to edit the values stored in a .XML file with php, look:

    this is the XML file:
    
    <?xml version="1.0" encoding="iso-8859-1"?>
    <dmx_signatures>
    <option1>1</option1>
    <option2>0</option2>
    </dmx_signatures>
    
    PHP:
    I will add many options there and I want to be able to edit this using PHP because I will use a form. I already know how to load the XML file and how to print data, but I really would like someone to explain to me how to edit a value and then save the xml file.

    this is how I open & print the xml info:
    
    <?php
    if (file_exists('dmx_signatures.xml')) {
        $xml = simplexml_load_file('dmx_signatures.xml');
    	
    	echo $xml->option2;
    } else {
        exit('ERROR: could not open xml file.');
    }
    ?>
    
    PHP:
    any help would be greatly appreciated !
     
    Shimurai, Jun 24, 2011 IP
  2. web.business

    web.business Greenhorn

    Messages:
    30
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    16
    #2
    you need to use Document Object Model ,this object has methods that enable you to add,edit,del ... the elements of the xml file and save it .
     
    web.business, Jun 24, 2011 IP
  3. mfscripts

    mfscripts Banned

    Messages:
    319
    Likes Received:
    4
    Best Answers:
    8
    Trophy Points:
    90
    Digital Goods:
    3
    #3
    mfscripts, Jun 25, 2011 IP
  4. exodus

    exodus Well-Known Member

    Messages:
    1,900
    Likes Received:
    35
    Best Answers:
    0
    Trophy Points:
    165
    #4
    Look at the following link:

    http://uk.php.net/manual/en/simplexmlelement.asxml.php

    
    jcr at di dot uminho dot pt 25-Jan-2011 10:32
    Code snippet to load a XML document, increment an attribute and store it again.
    My XML looks like:
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <doctypes counter="16">
        <doctype id="d1">
            <name>Carta</name>
            <acro>CA</acro>
        </doctype>
    ...
    </doctypes>
    
    I want to retrieve the counter attribute, increment it, and store the new document at the end:
    
    <?php
      $document = simplexml_load_file("mydoc.xml");
      $cont = (integer) $document['counter'];
      $document['counter'] = $cont+1;
      $document->asXML("mydoc.xml");
    ?>
    
    Code (markup):
    That makes it easy to save the xml object back to a file after your doing editing anything with it.
     
    exodus, Jun 26, 2011 IP