Dynamic XML in PHP

Discussion in 'PHP' started by pradeep, Mar 19, 2007.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in

    Creating dynamic XML with PHP



    When working with XML-based applications, developers often find themselves facing the requirement to generate XML-encoded data structures on the fly. Examples of this include an XML order template based on user input in a Web form, or an XML representation of a server request or client response based on run-time parameters.

    Although this task might seem intimidating, it's actually quite simple when one takes into account PHP's sophisticated DOM API for dynamic node construction and manipulation. In this article, you will get know the main functions in this API, showing you how to programmatically generate a complete well-formed XML document from scratch and save it to disk.

    Note: This article assumes a working Apache/PHP5 installation with the DOM functions enabled, and a working knowledge of basic XML constructs such as elements, attributes and CDATA blocks. You can obtain an introduction to these topics from the introductory material at Melonfire (http://melonfire.com/community/columns/trog/article.php?id=78 and http://melonfire.com/community/columns/trog/article.php?id=79)

    Creating the Doctype declaration



    Let's start right at the top, with the XML declaration. In PHP, this is fairly simple; it only requires you to instantiate an object of the DOMDocument class and supply it with a version number. To see it in action type out the example script in Listing A.

    Listing A
    PHP:
    <?php
    // create doctype
    $dom = new DOMDocument("1.0");

    // display document in browser as plain text
    // for readability purposes
    header("Content-Type: text/plain");

    // save and display tree
    echo $dom->saveXML();
    ?>
    Notice the saveXML() method of the DOMDocument object -- I'll come back to this later, but for the moment simply realise that this is the method used to output a current snapshot of the XML tree, either to a file or to the browser. In this case, I've sent the output directly to the browser as ASCII text for readability purposes; in real-world applications, you would probably send this with a Content-Type: text/xml header.

    When you view the output in your browser, you should see something like this:

    Code:
    <?xml version="1.0"?>

    Adding elements and text nodes



    Now that's all very pretty and fine, but the real power of XML comes from its elements and the content they enclose. Fortunately, once you've got the basic DOMDocument initialised, this becomes extremely simple. There are two steps to the process:

    1. For each element or text node you wish to add, call the DOMDocument object's createElement() or createTextNode() method with the element name or text content. This will result in the creation of a new object corresponding to the element or text node.

    2. Append the element or text node to a parent node in the XML tree by calling that node's appendChild() method and passing it the object produced in the previous step.

    An example will make this clearer. Consider the script in Listing B.

    Listing B
    PHP:
    <?php
    // create doctype
    $dom = new DOMDocument("1.0");

    // display document in browser as plain text
    // for readability purposes
    header("Content-Type: text/plain");

    // create root element
    $root $dom->createElement("toppings");
    $dom->appendChild($root);

    // create child element
    $item $dom->createElement("item");
    $root->appendChild($item);

    // create text node
    $text $dom->createTextNode("pepperoni");
    $item->appendChild($text);

    // save and display tree
    echo $dom->saveXML();
    ?>
    Here, I've first created a root element named <toppings> and attached it to the XML header. Next, I've created an element named <item> and attached it to the root element. And finally, I've created a text node with the value "pepperoni" and attached it to the <item> element. The result should look like this:

    Code:
    <?xml version="1.0"?>
    <toppings>
    	<item>pepperoni</item>
    </toppings>
    If you'd like to add another topping, simply create another <item> and populate it with different content (Listing C).

    Listing C
    PHP:
    <?php
    // create doctype
    $dom = new DOMDocument("1.0");

    // display document in browser as plain text
    // for readability purposes
    header("Content-Type: text/plain");

    // create root element
    $root $dom->createElement("toppings");
    $dom->appendChild($root);

    // create child element
    $item $dom->createElement("item");
    $root->appendChild($item);

    // create text node
    $text $dom->createTextNode("pepperoni");
    $item->appendChild($text);

    // create child element
    $item $dom->createElement("item");
    $root->appendChild($item);

    // create another text node
    $text $dom->createTextNode("tomato");
    $item->appendChild($text);

    // save and display tree
    echo $dom->saveXML();
    ?>
    And here's the revised output:

    Code:
    <?xml version="1.0"?>
    <toppings>
    	<item>pepperoni</item>
    	<item>tomato</item>
    </toppings>

    Adding attributes



    You can also add qualifying information to your elements, through the thoughtful use of attributes. With the PHP DOM API, attributes are added in a two-step process: first create an attribute node holding the name of the attribute with the DOMDocument object's createAttribute() method, and then append a text node to it holding the attribute value. Listing D is an example.

    Listing D
    PHP:
    <?php
    // create doctype
    $dom = new DOMDocument("1.0");

    // display document in browser as plain text
    // for readability purposes
    header("Content-Type: text/plain");

    // create root element
    $root $dom->createElement("toppings");
    $dom->appendChild($root);

    // create child element
    $item $dom->createElement("item");
    $root->appendChild($item);

    // create text node
    $text $dom->createTextNode("pepperoni");
    $item->appendChild($text);

    // create attribute node
    $price $dom->createAttribute("price");
    $item->appendChild($price);

    // create attribute value node
    $priceValue $dom->createTextNode("4");
    $price->appendChild($priceValue);

    // save and display tree
    echo $dom->saveXML();
    ?>
    And here's what the output will look like:
    Code:
    <?xml version="1.0"?>
    <toppings>
    	<item price="4">pepperoni</item>
    </toppings>

    Adding CDATA blocks and processing instructions



    While not used quite as often, CDATA blocks and processing instructions (PI) are also well-supported by the PHP API, through the DOMDocument object's createCDATASection() and createProcessingInstruction() methods. Listing E shows you an example.

    Listing E
    PHP:
    <?php
    // create doctype
    $dom = new DOMDocument("1.0");

    // display document in browser as plain text
    // for readability purposes
    header("Content-Type: text/plain");

    // create root element
    $root $dom->createElement("toppings");
    $dom->appendChild($root);

    // create child element
    $item $dom->createElement("item");
    $root->appendChild($item);

    // create text node
    $text $dom->createTextNode("pepperoni");
    $item->appendChild($text);

    // create attribute node
    $price $dom->createAttribute("price");
    $item->appendChild($price);

    // create attribute value node
    $priceValue $dom->createTextNode("4");
    $price->appendChild($priceValue);

    // create CDATA section
    $cdata $dom->createCDATASection("\nCustomer requests that pizza be sliced into 16 square pieces\n");
    $root->appendChild($cdata);

    // create PI
    $pi $dom->createProcessingInstruction("pizza""bake()");
    $root->appendChild($pi);

    // save and display tree
    echo $dom->saveXML();
    ?>
    And here's the output:

    Code:
    <?xml version="1.0"?>
    <toppings>
    	<item price="4">pepperoni</item>
    	<![CDATA[
    	Customer requests that pizza be sliced into 16 square pieces
    	]]>
    	<?pizza bake()?>
    </toppings>

    Saving the results



    Once you've got the tree the way you want it, you can either save it to a file or store it in a PHP variable. The former function is performed by calling the save() method with a file name, while the latter is performed by calling the saveXML() method and assigning the result to a string. Here's an example (Listing F).

    Listing F
    PHP:
    <?php
    // create doctype
    $dom = new DOMDocument("1.0");

    // create root element
    $root $dom->createElement("toppings");
    $dom->appendChild($root);
    $dom->formatOutput=true;

    // create child element
    $item $dom->createElement("item");
    $root->appendChild($item);

    // create text node
    $text $dom->createTextNode("pepperoni");
    $item->appendChild($text);

    // create attribute node
    $price $dom->createAttribute("price");
    $item->appendChild($price);

    // create attribute value node
    $priceValue $dom->createTextNode("4");
    $price->appendChild($priceValue);

    // create CDATA section
    $cdata $dom->createCDATASection("\nCustomer requests that pizza be sliced into 16 square pieces\n");
    $root->appendChild($cdata);

    // create PI
    $pi $dom->createProcessingInstruction("pizza""bake()");
    $root->appendChild($pi);

    // save tree to file
    $dom->save("order.xml");

    // save tree to string
    $order $dom->save("order.xml");
    ?>
    That's it. Hopefully you found this article interesting, and will be able to use these techniques in your daily work with XML.
     
    danieljames123 and abilondias like this.
  2. abilondias

    abilondias New Member

    Joined:
    Jan 19, 2011
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    1
    Occupation:
    I dont work yet
    Hi,

    Liked so much your article,
    I have a basic knowledge on PHP, but i dont know what is the "->"

    Thanks,

    ~abilondias
     
  3. shrikrishnatech

    shrikrishnatech New Member

    Joined:
    Nov 19, 2010
    Messages:
    42
    Likes Received:
    4
    Trophy Points:
    0
    Occupation:
    Wordpress theme, Wordpress Theming, WP Themes, Cor
    Home Page:
    http://www.shrikrishnatechnologies.com
  4. danieljames123

    danieljames123 Banned

    Joined:
    May 5, 2011
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    http://www.biztechconsultancy.com
    Thanks to share this
     
  5. kumkum01

    kumkum01 New Member

    Joined:
    Apr 13, 2011
    Messages:
    10
    Likes Received:
    0
    Trophy Points:
    0
    Hi.....I think it is very nice sharing in here.........thanks a lot.......:charming::charming:
     
  6. tanmayk

    tanmayk New Member

    Joined:
    Feb 2, 2012
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Thank you so much...excellent post!!

    Just what i needed.!
     
  7. jamewhite86

    jamewhite86 New Member

    Joined:
    Jan 30, 2012
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    http://hostnsoft.com/webhosting/
    it's actually quite simple when one takes into account PHP's sophisticated DOM API for dynamic node construction and manipulation. really a lot of information share in your website. thanks
     
  8. Scripting

    Scripting John Hoder

    Joined:
    Jun 29, 2010
    Messages:
    421
    Likes Received:
    57
    Trophy Points:
    0
    Occupation:
    School for life
    Location:
    /root
    Well explained tutorial. Keep it up!
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice