Thursday, February 7, 2013

PHP XMLWriter

PHP XMLWriter

    This example demonstrates How to generate XML content in memory using XMLWriter object.


Step 1) Create XMLWriter object

   $writer =  new XmlWriter();

Step 2)  Open in Memory Connection and assign it to XmlWriter

$writer->openMemory();

Step 3) Create Document Declaration/Xml Processing Instruction

$writer->startDocument("1.0","utf-8");

Step 4)   Optional filed Set Indentation

$writer->setIndent(true);

Step 5)  Write  Start Element/root element in this xml.

$writer->startElement("bookslist");

Step 6) Write remaining elements under root element(step 5).

book node has title,price,publisher and authors list.  

Each node has start element & end element.
if node has data  use text method to write content to that element.

$writer->startElement("book");
$writer->startAttribute("id"); //writing id attribute to book's node.
$writer->text("ISBN-978-3-16-148410-0");
$writer->endAttribute();
$writer->startElement("title"); //start element name title
$writer->text("PHP programming");//write text to that title
$writer->endElement(); //end the title element.
//repeates above process for remaining elements.

$writer->startElement("Price");
$writer->text("$33.39");
$writer->endElement();

$writer->startElement("publisher");
$writer->text("Sams");
$writer->endElement();
//book has 1 or more authors in that case
//authors root node has author sub node which has firstname and lastname,
//you can add as many author nodes to authors node.
//here we have 1 author.
$writer->startElement("authors");
$writer->startElement("author");
$writer->startElement("firstname");
$writer->text("jhon");
$writer->endElement();
$writer->startElement("lastname");
$writer->text("solomon");
$writer->endElement();
$writer->endElement();

$writer->endElement();

Step 7)  Close StartElement tag here
$writer->endElement();

Step 8)  Close Document

$writer->endDocument();

Step 9)  See output.

echo $writer->outputMemory()."<br>";


Step 10) Here is the output.(if u see only content in the browser then context menu has View Page Source )

OUTPUT

<bookslist>
 <book id="ISBN-978-3-16-148410-0">
  <title>PHP programming</title>
  <Price>$33.39</Price>
  <publisher>Sams</publisher>
  <authors>
   <author>
    <firstname>jhon</firstname>
    <lastname>solomon</lastname>
   </author>
  </authors>
 </book>
</bookslist>

Tags:PHP XmlWriter,XMLWriter::setInden,XMLWriter::startDocument,
XMLWriter::endDocument,XmlWriter::startElement,XmlWriter::EndElement,XMLWriter::text,
XMLWriter::outputMemory,XMLWriter::openMemory, Writing XML content in PHP,Generating XML content in PHP.

No comments:

Post a Comment