Create XML with PHP DOM

Usually while we are working on xml-based or on API, developers are need to create XML-encoded data structure on fly. Following sample code will explain you how to create XML using DOM

    header("Content-Type: text/plain");
    $doc = new DOMDocument('1.0', "UTF-8");
    $doc->formatOutput = true;
    $productList = $doc->createElement("ProductList");
    $doc->appendChild( $productList );

    $product = $doc->createElement( "Product" );

    $name = $doc->createElement( "name" );
    $product->appendChild( $name );

    $description = $doc->createElement("Description");
        $doc->createTextNode("This is test product description..!!!")
    $product->appendChild( $description );

    $price = $doc->createElement("Price");
    $product->appendChild( $price );

    $stockItems = $doc->createElement("StockItems");
        $stock = $doc->createElement("Stock");
            $name = $doc->createElement("Name");
            $stock->appendChild( $name );
            $onHandValue = $doc->createElement("OnHandValue");
            $stock->appendChild( $onHandValue );
        $stockItems->appendChild( $stock );
    $product->appendChild( $stockItems );
    $productList->appendChild( $product );
    echo $doc->saveXML();
    /* $doc->save("productlist.xml"); */

In above code,

– new DOMDocument(‘1.0’, “UTF-8”); will create DOM object for xml with argument 1.0 and encoding formate UTF-8

– createElement(“ProductList”), to create xml node “ProductList”

– $doc->appendChild( $productList ), append node to xml

– Create child node: to create child node we need to append child object node to its parent node object,  i.e. $product element to its parent element $productList. Here product is child of product list

– $doc->saveXML(), will create xml on fly and give the output on browser

Once we get the XML the way we want we can store get its value to string variable or it can also be store to server/system with given name and destination path as bellow,


You will get following output with this,

<?xml version="1.0" encoding="UTF-8"?>
  <Product product_id="13">
    <Description>This is test product description..!!!</Description>

2 thoughts on “Create XML with PHP DOM

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s