How to Remove a Child From XML With PHP

How to Remove a Child From XML With PHP thumbnail
The PHP DOMNode class manipulates XML documents

Web applications developers use the popular PHP scripting language to present dynamic data to their website visitors. Developers may design the PHP script to retrieve and store the data in XML formatted documents. The PHP DOMNode class accesses the XML document and manipulates the data using several different predefined methods. Specifically, the "removeChild" method removes an XML child element.

Instructions

    • 1

      Assign the new DOMDocument action to a variable. In this example code, the new DOMDocument action has been assigned to the retriever variable.

      $retriever = new DOMDocument();

    • 2

      Load your XML document into the script. In this example, "yourFile.XML" has been loaded and assigned to the retriever variable.

      $retriever ->load( 'yourFile.xml' );

    • 3

      Get and assign the document element to a new variable. Here, "documentElement" has been assigned to the $masterElement variable.

      $masterElement = $retriever->documentElement ;

    • 4

      Select the child element that you wish to remove. Use the getElementsbyTagName method. In this example, the "yourElement" element is selected and assigned to the masterContent variable.

      $masterContent = $masterElement->getElementsByTagName('yourElement')->item(0);

    • 5

      Remove the child element using the removeChild method. The example code uses the removeChild method to remove the content that was assigned to the $masterContent variable.

      $oldContent = $masterElement->removeChild($masterContent );

    • 6

      Print out the XML to ensure the child element has been removed. Use the echo command and the saveXML method.

      echo $retriever->saveXML();

      After being enclosed within PHP tags, the entire sample code appears as:

      <?php

      $retriever = new DOMDocument();

      $retriever ->load( 'yourFile.xml' );

      $masterElement = $retriever->documentElement;

      $masterContent = $masterElement->getElementsByTagName('yourElement')->item(0);

      $oldContent = $masterElement->removeChild($masterContent );

      echo $retriever->saveXML();

      ?>

Related Searches:

References

  • Photo Credit Comstock/Comstock/Getty Images

Comments

Related Ads

Featured