A Scripting Language for Web, Linux and Windows

A Scripting Language for Web, Linux and Windows

Example: Work with XML documents

Demonstrates how to work with libXML2 library.
libXML2 functions are defined in lib/xml2.inc.v1

Note: You have to install libXML2 libraries. On Windows copy the 32-Bit DLL's from HERE into the home directory of V1 where v1.exe is located.

Read also libXML2 documentation: http://xmlsoft.org/html/

<?php <?v1
require_once ("lib/xml2.inc.v1");

// Parse XML file as array and dump it
xmlTree = array ();
parseXMLFile ("test.xml", xmlTree);
print_r (xmlTree);

// Parse XML string as array and dump it
xmlStr = '
<?xml version="1.0" encoding="ISO-8859-1"?>
<EXAMPLE version="1.0">
    <!--This is a comment.-->
    <HEADER>
        <X_ORDER_ID type="1">0000053535</X_ORDER_ID>
        <CUSTOMER_ID>00100</CUSTOMER_ID>
    </HEADER>
</EXAMPLE>';

xmlTree = array ();
parseXMLString (xmlStr, xmlTree);
print_r (xmlTree);

// Write XML
const MY_ENCODING = "ISO-8859-1";

doc = null;
buf = xmlBufferCreate ();
writer = xmlNewTextWriterMemory (buf, 0);
if (!writer) {
    print ("xmlNewTextWriterMemory failed.");
    exit (1);
}

xmlTextWriterStartDocument (writer, null, MY_ENCODING, null);

xmlTextWriterWriteAttribute (writer, "version",  "1.0");
xmlTextWriterStartElement (writer, "EXAMPLE");
xmlTextWriterWriteComment (writer, "This is a comment.");
xmlTextWriterStartElement (writer, "HEADER");
xmlTextWriterWriteElement (writer, "X_ORDER_ID", sprintf ("%010d", 53535));
xmlTextWriterWriteElement (writer, "CUSTOMER_ID",  "00100");
xmlTextWriterEndElement (writer); // Close <HEADER>
xmlTextWriterEndElement (writer); // Close <EXAMPLE>

xmlTextWriterEndDocument (writer);
xmlFreeTextWriter (writer);

// Save XML file
if (buf) {
  str = xmlBufferGetString (buf);
  fwrite (fopen ("test.xml", "w+"), str);
  xmlBufferFree (buf);
}

?>

back to Home