XML programming using PHP and Ajax

Source: Internet
Author: User
Tags contains http request object model php and php code web services wrapper xquery
Ajax|xml| programming in an SOA architecture, programmers often use XML to exchange structured and semi-structured data between applications. XML and its related technologies-Document Object Model (Model,dom), XPath, HTTP, XQuery, and Extensible Stylesheet Language Transformations (extensible Stylesheet Language TRANSFORMATIONS,XSLT)-Provides a powerful environment for rapid application development. Applications built on these technologies will consume smaller memory space, require lower maintenance costs, and have higher quality and flexibility.

The XML aspects of DB2 and other relational databases are already quite mature, so they are ideal for storing and managing XML data in addition to storing and managing relational data. DB2 9 XML Support (called PureXML) provides the ability to store XML in the form of pure XML (in other words, annotated, tree-like tiered storage). In DB2 9, XML data can be indexed in XML schemas, can be combined from relational data, can be decomposed into relational data, can be queried and transformed, can be published independently, or combined using sql/xml and XQuery with relational data.

Web browsers are also providing more functionality for client scripts to efficiently process XML. By using asynchronous JavaScript and XML (asynchronous JavaScript and Xml,ajax), Web pages can now make remote procedure calls directly to the application server and can use the DOM APIs on any returned XML data.

This article will show you how to write simple xml-based applications with the capabilities of DB2 XML, Ajax, and PHP hypertext Preprocessor (PHP). With the help of the sample scenario, you will learn how to invoke PHP applications in JavaScript, how to modify XML data using the DOM and SimpleXML APIs, how to transfer XML from the client to the application to the database, and how to create a PHP Web service to use the Sql/xml and XQuery Publish reports about XML data.

   XML Benefits

Most applications are used to create, store, manipulate, and render business data. Object wrapping refers to tying business data together so that business logic can handle them more easily. Many of the functions of these wrapper objects are to provide the structure of business data based on relational and formatting rules, and to enable business logic to manipulate, publish, and serialize encapsulated data.

Figure 1. Object Wrapper-based applications

Figure 1 illustrates a sample life insurance application that uses the object wrapper. Each box represents an object, with at least one object:

• A constructor

· Getter and Setter methods

• Validating code

• Serialization of internal object hierarchies

These objects are not related to the actual business logic. Object wrapping is designed to make business logic easier to manage business data. The code needed to wrap the data is much more than the business logic. More code will lead to more bugs, greater retention, more maintenance, and higher costs.

If a data variable in an object can be formatted as an XML structure, and the object's primary role is to expose the data to business logic and let business logic manipulate them, you can replace the object with a DOM.

Figure 2. XML-based applications

Figure 2 shows a sample insurance application that uses the XML and DOM wrappers. All the data wrapper objects in Figure 1 are replaced with a DOM object. Business data is modeled in XML, and the DOM provides the necessary APIs to:

• Create a new XML object.

• Update the value of an XML object.

• Navigating XML objects.

• Search in the object hierarchy using XPath.

• Serialization and drag of the row XML object hierarchy (in other words, built-in persistence).

By using XML, you can avoid using most wrapper objects that manage business data. Applications will become more concise and more focused on business logic than on data management.

   XML and Schemas

Introducing XML into a schema can provide a standardized way of representing business data. XML can provide the structure of data; XML schemas impose structural and formatting rules, and languages such as the DOM API and XQuery, XPath, and XSLT enable business logic to manipulate, publish, and serialize data efficiently. Because the XML representation of business data is consistent across the client, middle tier, and database, the code that manipulates these objects is similar.

I'll show you how to build an xml-based application in a three-tier environment, which consists of the following parts:

· WEB Client: Asynchronous JavaScript and XML (Ajax), DOM

• Application Server: PHP and SimpleXML

• Database: DB2 9 and Sql/xml,xquery
   scenarios based on the ACORD life data Model

Let's consider a simple life insurance scenario in which you first create an XML document that represents a new policy, then query and manipulate the document, and move the document from one layer to another. This document is based on the XML for the life Insurance specification of the Cooperative Operations Research and Development Association (Association for Cooperative Operations Study & Development,acord), It defines the data that health insurance and annuity insurance need to exchange.

In order to apply for a new insurance, the customer needs to provide some basic information. Part of the information is filled in a PHP application, and part of it is in the client browser. The policy is then stored in a DB2 XML column. In DB2 9, XML-type columns store XML data internally as a parsed tree, stored in different places with relational data. This approach is DB2 9-specific, and the earlier DB2 version uses the relational storage infrastructure to store the XML.

The following is the process of the policy XML document between the client and the application:

• In the Web client, the Customer updates the page and clicks Submit.

· The WEB client sends a XMLHTTP request to PHP to obtain a new blank policy document.

· The PHP application opens a blank policy document, updates it with a globally unique identifier (GUID), and then returns the document to the Web client.

· The Web client uses Ajax to capture the returned event, retrieves the XML DOM, and populates the document with the information entered in the Web page.

· The WEB client uses XMLHTTP to send the updated XML to the PHP application.

Figure 3. A Web site that creates a new policy request.

Figure 3 shows a Web page that is used to create a new policy request. When the user clicks the Submit button, the JavaScript function Submitpolicy () is invoked (see Listing 1). This function sends an HTTP request to the PHP application createnewpolicy.php to obtain a blank policy. It also sets a callback function, Fillpolicy (), that is used to catch events that are returned from HTTP requests.


When the first request arrives at the middle-tier PHP application Server, a new XML policy document is loaded into the SimpleXML object. Update the Transrefguid element with the GUID created in the PHP application by using the SimpleXML API.

Header (' Content-type:text/xml ');

$fileContents = file_get_contents ("$basedir/acord.xml");

$dom = simplexml_load_string ($fileContents);

$dom->txliferequest->transrefguid= $guid;

echo $dom->asxml ();

The document is then sent to the client.

For this article, we assume that the GUID is created by a mechanism, such as a combination of time and random numbers. It is more important to understand how the XML document that represents the policy is treated as an in-memory business object hierarchy and how to use the SimpleXML API (or Dom/xpath) to navigate and update the object.

   populating basic Customer Information

In the Web client, the Fillpolicy () function reads the returned value. Now, a DOM object that contains an in-memory representation of the returned XML can be used to manipulate the policy document. The information that the customer enters on the Web page is used directly to update the DOM. After updating the policy with customer information, use XMLHTTP to submit the modified DOM object back to the PHP application (see Listing 2). Even HTML component values are read with the Dhtmldocument Object Model (DOM).

   store policy in DB2

The PHP application stores the incoming XML document directly in the database without having to parse it (see Listing 3). DB2 's PureXML support will implicitly parse incoming XML and store it in a hierarchical hierarchy of class DOM. You can now query XML in XQuery statements using XML navigation techniques such as XPath, as used in the DOM. DB2 9 also provides the ability to index on any node in the hierarchy.


   exposing a service on an XML document

After the new policy is stored in DB2 9, the insurance agent can inquire about the policy to decide whether to accept the insurance. Queries for obtaining new policy reports are exposed to client applications through WEB services.

The Web service in this example is written in PHP, which provides a concise interface for invoking the DB2 stored procedures of the business and transformation logic that implements the service. Each DB2 stored procedure consists of a sql/xml query that filters and transforms the XML policies stored in the database to create an output XML document. The PHP Web service then returns the XML document to the client.

Let's analyze each stored procedure to see those queries that effectively compose the WEB service implementation.


List DB2 inquiries for all new customer insurance. The stored procedure that contains the query is Listallnewcustomers (see Listing 4). This query searches for all policy documents in the INFO column of the ACORD table. In each XML document, the DB2 is further parsed to return only those documents where the code value of the policystatus/@tc property is set to 12 (that is, the recommended value). The query output is an XML document that has a root node newpolicylist, which contains a series of txlife subnodes for each new policy (see Figure 4).

Figure 4. Return sql/xml query for new policy list

Notice how this query first uses the DB2 XQuery function Db2-fn:xmlcolumn to navigate the relational schema to navigate to the XML column db2admin. Acord.info. When it reaches an XML column, it further uses XPath to navigate to the appropriate node in the XML schema (similar to navigating the DOM using PHP, JavaScript, or other languages).

List the DB2 inquiries for the proposed insurance of the risk customers. The query lists only new customers at risk (that is, they answered yes for a medical question). The query is contained in a stored procedure named Listatrisknewcustomers (see Listing 5). NOTE: The WHERE clause examines both the answer and the policy state.


DB2 queries that assess the risk of new customers at risk. For each policy in the above list, only questions that answer yes are listed in the health risk area of the policy. The query also returns Policytype to show how much the policy is worth in order to assess the risk. The stored procedure that contains the query (see Listing 6) is Getriskquestions (GUID). Note: You need a DB2 driver version that supports XML types. Otherwise, you will need to use xmlserialize in each stored procedure to serialize the XML value from the xmlquery. See developerWorks article "using DB2 native XML with PHP" For more detailed information.

   Creating a Web service

The PHP code for the Getnewpolicyinfo Web service is a thin wrapper that examines the type of policy report required and invokes the appropriate stored procedure. The value returned by the stored procedure is then sent back to the client (see Listing 7). Note how simple it is to create a Web service in PHP. The last three rows this feature is exposed as a Web service. A WEB service can be invoked on any client, including in a PHP application, as shown in Listing 8.



   Concluding remarks

In the past few years, XML support has matured across the application tiers, leading to the emergence of a powerful development environment that can change the way enterprise applications are designed. XML enables developers to define rules and structures for business documents, as well as to instantiate documents in memory as layered objects, and developers can navigate, modify, and serialize such objects using standard APIs at any level. Ajax enables web-based client scripts to invoke the DOM API, as well as remote procedure calls to the middle tier. PHP provides one of the easiest ways to process XML and WEB services, so it is ideal for xml-based application development. The last strand of XML evolution is the database layer. DB2 9 enables the database layer to manipulate XML. So this evolution cycle is over.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.