Delete element in xml file by using php

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Samudaya

    #1

    Delete element in xml file by using php

    Hi,
    I have a application which has a xml file reading and wrting. I want
    to remove some element in xml file by using php.


    <?xml version="1.0" encoding="UTF-8"?>
    <element1>
    <subelement1>aa </subelement1>
    <subelement2>aa </subelement2>
    </element1>


    How to remove "<subelement1>a a</subelement1>" that elements and save
    back to same or other xml file.
  • Curtis

    #2
    Re: Delete element in xml file by using php

    Samudaya wrote:
    Hi,
    I have a application which has a xml file reading and wrting. I want
    to remove some element in xml file by using php.
    >
    >
    <?xml version="1.0" encoding="UTF-8"?>
    <element1>
    <subelement1>aa </subelement1>
    <subelement2>aa </subelement2>
    </element1>
    >
    >
    How to remove "<subelement1>a a</subelement1>" that elements and save
    back to same or other xml file.
    Check out the PHP manual:

    SimpleXML: <URL:http://www.php.net/manual/en/book.simplexml. php>
    DOM (PHP 5): <URL:http://www.php.net/manual/en/intro.dom.php>

    If you're stuck with PHP 4:
    <URL:http://www.php.net/manual/en/ref.domxml.php>

    --
    Curtis (http://dyersweb.com/)

    Comment

    • macca

      #3
      Re: Delete element in xml file by using php

      <?xml version="1.0" encoding="UTF-8"?>
      <element1>
          <subelement1>aa </subelement1>
          <subelement2>aa </subelement2>
      </element1>
      >
      How to remove  "<subelement1>a a</subelement1>" that elements and save
      back to same or other xml file.
      first of all, i wouldnt call each element element1 and element2 etc
      just element. You can store the meta data such as a number as an
      attribute instead. I'd do something like this (off the top of my head
      and untested)...


      $xml = <<<XML
      <?xml version="1.0" encoding="UTF-8"?>
      <element num="1">
      <subelement1>aa </subelement1>
      <subelement2>aa </subelement2>
      </element>
      </xml>
      XML;

      $dom = new DOMDocument();
      $dom->loadXML($xml );

      $xpath = new DomXpath($dom);

      $result = $xpath->query("//element");
      $result->parentNode->removeChild($r esult->item(0));

      $dom->saveXML();

      Comment

      Working...