Sunday

Using PHP 4's DOM XML functions to create XML files from SQL data

Intended Audience

This tutorial is intended for developers who wish to extract data from a database and insert it into XML files so that it can be processed in some way, usually by transforming it into HTML using an XSL file.

This method completely splits the presentation layer (i.e. the generation of HTML documents) from the business layer (the application of business rules using a language such as PHP) so that any one of these layers can be modified without affecting the other.

In the samples below the code is generic in that no column names are ever hard coded. Data is retrieved from the database as an associative array (a series of 'name=value' pairs), and every element of the array is extracted and transferred to the XML file. The contents of the associative array are therefore governed entirely by the SQL 'select' statement.

In the samples below I will show how to deal with data from a single table, and then data from two tables with a one-to-many relationship. Finally I will show how to insert additional data in the form of XML attributes.

Prerequisites

The sample code requires that you have the DOM XML extension available in your PHP installation. It is also assumed that you know what an XML file is and what it can be used for.

Please note that this extension has been removed from PHP 5 and moved to the PECL repository. For details on how to use the DOM extension instead please refer to Using PHP 5's DOM functions to create XML files from SQL data

Multiple occurrences of a single table

The following code will take the contents of $dbresult (any number of rows, each of which contains a series of name=value pairs) and write it to a variable as an XML string. This can subsequently be written to a disk file or transformed into an HTML document using the Sablotron XSLT processor which is built into PHP. For details on how to use this extension please refer to Using PHP 4's Sablotron extension to perform XSL Transformations

This first piece of code simply connects to the database and performs a query:

$dbconnect = mysql_connect('localhost', 'user', 'pass')) {

echo "Connection failed to the host 'localhost'.";
exit;
} // if
if (!mysql_select_db('test')) {
echo "Cannot connect to database 'test'";
exit;
} // if

$table_id = 'some_table';
$query = "SELECT * FROM $table_id";
$dbresult = mysql_query($query, $dbconnect);

Now that we have our data we transfer it to an XML document. We start by creating a new DOM document. The following command will set the XML version number to '1.0' and return the object reference for the new document:

// create a new XML document

$doc = domxml_new_doc('1.0');

The first element we create in the XML document is known as the root element. Each XML document must have 1, and only 1, root element. In this example I have called it 'root', but you can use whatever name you like (such as the name of the PHP script which is executing). Note that you have to create the element and insert it into the document with two functions.

// create root node

$root = $doc->create_element('root');
$root = $doc->append_child($root);

Now we are ready to start adding the data we have retrieved from the database. Note that I am returning each row as an associative array which provides me with a list of 'name=value' pairs. This makes all subsequent processing far easier.

// process one row at a time

while($row = mysql_fetch_assoc($dbresult)) {

The first task I must perform for each row is to add a new element to the XML document. Here I create a new element using the table name, then I insert it into the document as a child of the root element.

  // add node for each row

$occ = $doc->create_element($table_id);
$occ = $root->append_child($occ);

Now I loop through each column in the current row, and insert the fieldname and corresponding value. You will see how having an associative array makes life easy. I need not concern myself with how many columns have been returned from the database query, nor with the order in which they are presented, as every column in the array gets written out.

  // add a child node for each field

foreach ($row as $fieldname => $fieldvalue) {

Note that here I create a new element for the field and then insert it as a child to the current database row, as identified in $occ.

    $child = $doc->create_element($fieldname);

$child = $occ->append_child($child);

Now I must add the field value as a text node, then insert it as a child element to the current field node, as identified in $child.

    $value = $doc->create_text_node($fieldvalue);

$value = $child->append_child($value);

These loops do not terminate until they have processed every column of every row which has been retrieved from the database.

  } // foreach

} // while

This next function returns the completed XML document as a string.

// get completed xml document

$xml_string = $doc->dump_mem(true);

Here I am simply outputting the results to the client browser, but I could just as easily perform some additional processing such as passing it to an XSLT processor for transformation into another document, such as an HTML document, using the contents of a separate XSL file.

echo $xml_string;

?>

The contents of the XML file produced with this code will look something like the following, starting with the XML declaration, with the version number, and immediately followed by the root node.

"1.0"?>


For each database row there will be an element, as a child to the root node, which contains the table name Each row element will have a separate child element for each column within that row. Note that each column element contains a text node for its value, while the row element does not have a text node. This grouping will be repeated for each column within each row. After the last column, notice the closing tag for the current row element, after which the row/column group must be repeated for each additional row that was extracted from the database and transferred to the XML file.

  

value1
value2
............
valueX


............

The last line in an XML file is there to close the root node.


Note that each element within the XML document has an opening and a closing tag in the format .... This identifies the node name within the document tree. Everything between these two tags is a child node to that element. This child node may be a text node or another element.

You may sometimes see an element in an XML document shown as . This signifies that the element is empty. When an element is empty, XML allows the opening and closing tags to be merged into a single self-closing tag.

A One-to-Many relationship

In the following example the XML string will contain data from two tables arranged in a One-to-Many (or parent-to-child or outer-to-inner) relationship. In the following code two query results are produced: $resouter for the parent table and $resinner for the child table. I shall only comment this code where there are differences.

$dbconnect = mysql_connect('localhost', 'user', 'pass')) {

echo "Connection failed to the host 'localhost'.";
exit;
} // if
if (!mysql_select_db('test')) {
echo "Cannot connect to database 'test'";
exit;
} // if

Here, for example, are separate database queries for each of the two tables:

$outer_table = 'parent_table';

$query = "SELECT * FROM $outer_table WHERE column='value'";
$resouter = mysql_query($query, $dbconnect);

$inner_table = 'child_table';
$query = "SELECT * FROM $inner_table WHERE column='value'";
$resinner = mysql_query($query, $dbconnect);

Here we create a new DOM document and add the root node:

// create a new XML document

$doc = domxml_new_doc('1.0');

// add root node
$root = $doc->create_element('root');
$root = $doc->append_child($root);

Here we add a node for the single row obtained from the parent table:

// add node for parent/outer table

$outer = $doc->create_element($outer_table);
$outer = $root->append_child($outer);

We must not forget to add each column value as a child element to the $outer node.

// take only one row from parent/outer table

$row = mysql_fetch_assoc($resouter);

// add a child node for each parent field
foreach ($row as $fieldname => $fieldvalue) {
$child = $doc->create_element($fieldname);
$child = $outer->append_child($child);
$value = $doc->create_text_node($fieldvalue);
$value = $child->append_child($value);
} // foreach

Here we add a node for each row obtained from the child table. Note that each of these rows is inserted as a child node to the $outer node, not the $root node. Each $inner node will have its column values inserted as its children.

// process all rows of the inner/many/child table

while($row = mysql_fetch_assoc($resinner)) {
// add node for each record
$inner = $doc->create_element($inner_table);
$inner = $outer->append_child($inner);
// add a child node for each field
foreach ($row as $fieldname => $fieldvalue) {
$child = $doc->create_element($fieldname);
$child = $inner->append_child($child);
$value = $doc->create_text_node($fieldvalue);
$value = $child->append_child($value);
} // foreach
} // while

Finally, get the completed XML document and send it to the client's browser.

// get completed xml document

$xml_string = $doc->dump_mem(true);
echo $xml_string;
?>

The above code will produce an XML file with the following structure:

"1.0"?>



value1
value2
............
valueX

value1
value2
............
valueX


............



This has the structure to to . The has child nodes which are its column values as well as multiple occurrences of .

Adding optional attributes

It may sometimes be necessary to include additional information for an element with the XML data, and this can be done in the form of attributes. An attribute has a name and a value, and any number of attributes can be added to an element. This must be done by using the '->set_attribute' method immediately after the '->append_child' method and before any '->create_text_node' method, as shown in the following code snippet:

$child = $doc->create_element($fieldname);

$child = $outer->append_child($child);
$child->set_attribute('attr1', 'attrval1');
$child->set_attribute('attr2', 'attrval2');
$value = $doc->create_text_node($fieldvalue);
$value = $child->append_child($value);

These attribute values will then appear within the element's start tag, as follows:

"1.0"?>



"attrval1" attr2="attrval2">value1
"attrval1" attr2="attrval2">value2
"attrval1" attr2="attrval2">value3


Note that you can insert attributes for row elements as well as column elements.

In my own application I use attribute values to specify the size of each column, so that it does not have to be hard-coded within the XSL file. For multi-line columns I pass values for both 'rows' and 'cols'.

I also use attributes to include any error messages. All error messages get inserted to an array called $errors where the key is the fieldname and the value is the message. The code to insert the error message into the XML document as an attribute of the field which generated the error is as simple as this:

if (isset($errors[$fieldname])) {

$child->set_attribute("error", $errors[$fieldname]);
} // if

Using Multi-Byte Characters

I had a slight problem recently when the data I output to my XML file contained characters with accents (as in à, è, í, ö and û). These were coming out all garbled until I discovered the reason why. It turns out that the internal encoding for libxml when storing the document is UTF-8, so you need to convert non UTF-8 encoded strings into UTF-8 when setting content. This requires the following changes to the code samples:

(1) Convert from default character set (refer to default_charset in file php.ini) to UTF-8 by inserting a single line as follows:

  foreach ($row as $fieldname => $fieldvalue) {

$child = $doc->create_element($fieldname);
$child = $inner->append_child($child);
$value = mb_convert_encoding($value,'UTF-8','ISO-8859-1'); <<-- new line $value = $doc->create_text_node($fieldvalue);
$value = $child->append_child($value);
} // foreach

(2) To output the document correctly you must convert back to the default character set by amending the following line:

$xml_string = $doc->dump_mem(true, 'ISO-8859-1');

NOTE: In order for this to work you must enable the Multi-Byte String functions in PHP.

Conclusion

By using this method I have been able to develop a generic mechanism for creating XML files based on the relationship of the database tables concerned. All I need do is specify the table names(s) and the selection criteria, and whatever comes out of the database will be transferred to an XML file for subsequent transformation into HTML using an XSL file.
By Tony Marston

Quercus for PHP

Quercus is Caucho Technology's 100% Java implementation of PHP 5 released under the Open Source GPL license. Quercus comes with many PHP modules and extensions like PDF, PDO, MySQL, and JSON. Quercus allows for tight integration of Java services with PHP scripts, so using PHP with JMS or Grails is a quick and painless endeavor.

With Quercus, PHP applications automatically take advantage of Java application server features just as connection pooling and clustered sessions.

Quercus implements PHP 5 and a growing list of PHP extensions including APC, iconv, GD, gettext, JSON, MySQL, Oracle, PDF, and Postgres. Many popular PHP application will run as well as, if not better, than the standard PHP interpreter straight out of the box. The growing list of PHP software certified running on Quercus includes DokuWiki, Drupal, Gallery2, Joomla, Mambo, Mantis, MediaWiki, Phorum, phpBB, phpMyAdmin, PHP-Nuke, Wordpress and XOOPS.

Quercus presents a new mixed Java/PHP approach to web applications and services where Java and PHP tightly integrate with each other. PHP applications can choose to use Java libraries and technologies like JMS, EJB, SOA frameworks, Hibernate, and Spring. This revolutionary capability is made possible because 1) PHP code is interpreted/compiled into Java and 2) Quercus and its libraries are written entirely in Java. This architecture allows PHP applications and Java libraries to talk directly with one another at the program level. To facilitate this new Java/PHP architecture, Quercus provides and API and interface to expose Java libraries to PHP.

The Quercus .war file can be run on Java application servers such as Glassfish, i.e. it can be run outside of Resin. This .war file includes the Quercus interpreter and the PHP libraries.

If you are new to Quercus, please check out:

Private cloud networks are the future of corporate IT

The future of corporate IT is in private clouds, flexible computing networks modeled after public providers such as Google and Amazon yet built and managed internally for each business's users, the analyst firm Gartner says.

Cloud computing hype centers largely around the outsourcing of IT needs to cloud services available over the Internet. While this trend is expected to accelerate, Gartner predicts it will also become standard for large companies to build their own highly automated private cloud networks in which all resources can be managed from a single point and assigned to applications or services as needed. "Our belief is the future of internal IT is very much a private cloud," says Gartner analyst Thomas Bittman."Our clients want to know 'what is Google's secret? What is Microsoft's secret?' There is huge interest in being able to get learnings from the cloud."
Bittman discussed Gartner's predictions in an interview with Network World, and will detail them again next month at the analyst firm's annual Data Center Conference in Las Vegas in a presentation titled "The Future of Infrastructure and Operations: The Engine of Cloud Computing."

While Bittman says it will take years for private clouds to develop, some early adopters are already "Google-izing" their own data centers. Bechtel, for instance, is using the software-as-a-service computing model internally to provide IT services to 30,000 users, in a project that relies heavily on server and storage virtualization. (Compare storage products.)

Server virtualization is key to building internal as well as external clouds, Bittman says, noting that Amazon hosts applications in Xen virtual machines. But server virtualization is only one of several necessary layers.

A meta operating system -- similar to VMware's recently developed Virtual Datacenter Operating System -- will be necessary to manage an enterprise's distributed resources as one computing pool, Bittman adds.

Specifically, the meta operating system is "a virtualization layer between applications and distributed computing resources … that utilizes distributed computing resources to perform scheduling, loading, initiating, supervising applications and error handling."

But the meta operating system only provides the muscles of a distributed environment, Bittman says. Another layer, which Gartner calls a service governor, will have to provide the brains, making decisions about where to allocate computing resources.
Say you have five business units and 100 applications -- some need ultra-fast performance and others don't. The service governor will decide which application gets what.

The technology "is evolving," Bittman says."This is not something that is just going to turn on."

Private clouds will take shape over the next few years, but perhaps only in large enterprises."Over time, a small business will not have economies of scale to make it worth staying in the IT business," Bittman says. Within five years, a huge percentage of small businesses will get most of their computing resources from external cloud providers, he predicts.

That's not to say enterprises with their own private clouds will shun cloud offerings that provide instant access to processing power and storage. Each company will manage a fixed capacity in-house and have access to external capacity from public providers when they need it -- sort of like overdraft protection in a bank account, Bittman says.

If a company experiences a sudden spike in demand, the meta operating system and service governor will arrange for extra capacity to be secured from outside sources. Users won't have any idea which server they are using or whether computing capacity is coming from inside or outside the enterprise, Bittman says. Layers of abstraction will permeate through the data center and users will be presented only with a services-oriented interface.

As public clouds evolve, enterprises will have many more choices, Bittman says. Today's cloud computing services boast of elasticity, the ability to scale resources up and down as needed at any time. Amazon's cloud computing service is called the Elastic Compute Cloud (EC2), for example.

But these services aren't truly elastic, in Bittman's view. Amazon charges a certain price for each virtual server and "if I want a slightly larger server, I have to buy another one. … I have to do it in chunks," he says.

Cloud vendors should move toward providing computing capacity in any increment customers want, he says. But that's just one of many hurdles to be overcome in the building of private and public clouds.

"It's going to take a long time for clouds to mature in all areas and have viable offerings that fit all needs," Bittman says.
by Jon Brodkin
courtsy: http://www.networkworld.com




Wednesday

NASA Open Source Software

NASA conducts research and development in software and software technology as an essential response to the needs of NASA missions. Under the NASA Software Release policy, NASA has several options for the release of NASA developed software technologies. These options now include Open Source software release. This option is under the NASA Open Source Agreement "NOSA".

The motivations for NASA to distribute software codes Open Source are:

  • To increase NASA software quality via community peer review
  • To accelerate software development via community contributions
  • To maximize the awareness and impact of NASA research
  • To increase dissemination of NASA software in support of NASA's education mission

Projects

BigView

BigView allows for interactive panning and zooming of images of arbitrary size on desktop PCs running linux. Additionally, it can work in a multi-screen environment where multiple PCs cooperate to ...

CODE

CODE is a software framework for control and observation in distributed environments. The basic functionality of the framework allows a user to observe a distributed set of resources, services, and ...

ECHO

The concept of ECHO has been many years in the making. The initial charter and Plan development began in June of 1998 and was called the Independent Information Management System ...

Geometry Manipulation Protocol (GMP)

The Geometry Manipulation Protocol (GMP) is a library which serializes datatypes between XML and ANSI C data structures to support CFD applications. This library currently provides a description of geometric ...

Growler

Growler is a C++-based distributed object and event architecture. It is written in C++, and supports serialization of C++ objects as part of its Remote Method Invocation, Event Channels, and ...

IND: Creation and Manipulation of Decision Trees from Data

IND is applicable to most data sets consisting of independent instances, each described by a fixed length vector of attribute values. An attribute value may be a number, one of ...

IPG Execution Service

The Execution Service allows users to submit, monitor, and cancel complex jobs. Each job consists of a set of tasks that perform actions such as executing applications and managing data. ...

JavaGenes

JavaGenes is a fairly general purpose evolutionary software system written in Java. It implements several versions of the genetic algorithm, simulated annealing, stochastic hill climbing and other search techniques. JavaGenes ...

Libibvpp

Libibvpp is a C++ wrapper around libibverbs, which is part of the OpenFabrics software suite (www.openfabrics.org). For the most part, Libibvpp provides a minimalistic C++ wrapper interface to libibverbs, while ...

Livingstone2

Livingstone2 is a reusable artificial intelligence (AI) software system designed to assist spacecraft, life support systems, chemical plants or other complex systems in operating robustly with minimal human supervision, even ...

Mariana

Mariana is an algorithm that efficiently optimizes the hyperparameters for Support Vector Machines for regression and classification. It currently uses Simulated Annealing for optimization but can be extended to use ...

Mesh

Mesh is a secure, lightweight grid middleware that is based on the addition of a single sign-on capability to the built-in public key authentication mechanism of SSH using system call ...

Mission Simulation ToolKit

The Mission Simulation Toolkit (MST) is a flexible software system for autonomy research. The MST was developed as part of the Mission Simulation Facility (MSF) project, which was started in ...

NodeMon

NodeMon is a resource utilization monitor tailored to the Altix architecture, but is applicable to any Linux system or cluster. It allows distributed resource monitoring via the Growler software infrastructure. ...

Pour

Pour is a framework for Periodic, On-Demand, and User-Specified Information Reconciliation that accepts periodic information updates, collects information on-demand as needed, and accepts user-specified information while presenting a single unified ...

ROBUS-2

The ROBUS-2 Protocol Processor (RPP) is a custom-designed hardware component implementing the functionality of the ROBUS-2 fault-tolerant communication system. The Reliable Optical Bus (ROBUS) is the core communication system of ...

sequenceMiner

sequenceMiner was developed to address the problem of detecting and describing anomalies in large sets of high-dimensional symbol sequences. sequenceMiner works by performing unsupervised clustering (grouping) of sequences using the ...

SLAB Spatial Audio Renderer

SLAB is a software-based, real-time virtual acoustic environment rendering system being developed as a tool for the study of spatial hearing. SLAB is designed to work in the personal computer ...

Surfer

Surfer is an extensible framework designed to select and rank grid resources where a resource is defined to be anything that may need selecting such as compute resources, storage resources, ...

Swim

Swim is a Software Information Metacatalog that gathers detailed information about the software components and packages installed on each grid resource. Information is currently gathered for Executable and Linking Format ...

Vision Workbench

The NASA Vision Workbench (VW) is a modular, extensible, cross-platform computer vision software framework written in C++. It was designed to support a variety of space exploration tasks, including automated ...

World Wind

World Wind allows any user to zoom from satellite altitude into any place on Earth, leveraging high resolution LandSat imagery and SRTM elevation data to experience Earth in visually rich ...
courtsy: nasa.gov

Tuesday

NASA Successfully Tests First Deep Space Internet

NASA has successfully tested the first deep space communications network modeled on the Internet.
Working as part of a NASA-wide team, engineers from NASA's Jet Propulsion Laboratory in Pasadena, Calif., used software called Disruption-Tolerant Networking, or DTN, to transmit dozens of space images to and from a NASA science spacecraft located about 20 million miles from Earth.

"This is the first step in creating a totally new space communications capability, an interplanetary Internet," said Adrian Hooke, team lead and manager of space-networking architecture, technology and standards at NASA Headquarters in Washington.

NASA and Vint Cerf, a vice president at Google Inc., in Mountain View, Calif., partnered 10 years ago to develop this software protocol. The DTN sends information using a method that differs from the normal Internet's Transmission-Control Protocol/Internet Protocol, or TCP/IP, communication suite, which Cerf co-designed.

The Interplanetary Internet must be robust to withstand delays, disruptions and disconnections in space. Glitches can happen when a spacecraft moves behind a planet, or when solar storms and long communication delays occur. The delay in sending or receiving data from Mars takes between three-and-a-half to 20 minutes at the speed of light.

Unlike TCP/IP on Earth, the DTN does not assume a continuous end-to-end connection. In its design, if a destination path cannot be found, the data packets are not discarded. Instead, each network node keeps the information as long as necessary until it can communicate safely with another node. This store-and-forward method, similar to basketball players safely passing the ball to the player nearest the basket means information does not get lost when no immediate path to the destination exists. Eventually, the information is delivered to the end user.

"In space today, an operations team must manually schedule each link and generate all the commands to specify which data to send, when to send it, and where to send it," said Leigh Torgerson, manager of the DTN Experiment Operations Center at JPL. "With standardized DTN, this can all be done automatically."

Engineers began a month-long series of DTN demonstrations in October. Data were transmitted using NASA's Deep Space Network in demonstrations occurring twice a week. Engineers use NASA's Epoxi spacecraft as a Mars data-relay orbiter. Epoxi is on a mission to encounter Comet Hartley 2 in two years. There are 10 nodes on this early interplanetary network. One is the Epoxi spacecraft itself and the other nine, which are on the ground at JPL, simulate Mars landers, orbiters and ground mission-operations centers.

This month-long experiment is the first in a series of planned demonstrations to qualify the technology for use on a variety of upcoming space missions. In the next round of testing, a NASA-wide demonstration using new DTN software loaded on board the International Space Station is scheduled to begin next summer.

In the next few years, the Interplanetary Internet could enable many new types of space missions. Complex missions involving multiple landed, mobile and orbiting spacecraft will be far easier to support through the use of the Interplanetary Internet. It also could ensure reliable communications for astronauts on the surface of the moon.

The Deep Impact Networking Experiment is sponsored by the Space Communications and Navigation Office in NASA's Space Operations Mission Directorate in Washington. NASA's Science Mission Directorate and Discovery Program in Washington provided experimental access to the Epoxi spacecraft. The Epoxi mission team provided critical support throughout development and operations.
courtsy: nasa.gov

Wednesday

Switch from file get contents to curl

Introduction

file_get_contents() is deprecated in favor of using the CURL libraries. You will occasionally run accross old code that uses the file_get_contents() that you want to use on servers with the file_get_contents functionality disabled. This shows how to convert from that function to the curl functions.
[edit]
file_get_contents code

$data = file_get_contents($remoteurl);
[edit]
curl code

//Initialize the Curl session
$ch = curl_init();

//Set curl to return the data instead of printing it to the browser.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//Set the URL
curl_setopt($ch, CURLOPT_URL, $URL);
//Execute the fetch
$data = curl_exec($ch);
//Close the connection
curl_close($ch);

//$data now contains the contents of $URL

Tuesday

PHP, JSON and JavaScript usage

Today i want to introduce you to jSON (JavaScript Object Notation), in short, it is a simple format designed to exchange data between different programming languages. I will show you how to create JavaScript object, convert it to JSON string, and send to PHP script, which will decode jSON string to readable format (for PHP). But that’s not all, PHP script will create it’s own data object encode it to jSON string and send it back. All communication between JavaScript and PHP will be done thru AJAX.

If you haven’t heared about jSON yet, then you can visit Wikipedia for more information. The other technology you need to be familiar with before reading this article is AJAX. If you need to, you can read my Introduction to AJAX post.

Last note before we start, i am constantly working to make my articles as useful for you as possible, so beginning from this tutorial in each of my programming tutorials, at the end of the article you will find complete source code for download.

JSON objects

Usually when it comes to JSON we have an encoded string in mind, however JSON is a subset of JavaScript and in this programming language it can be used as is, to create objects. Simple JavaScript object created using JSON notation can look like this:

/*

var
JSONstring =
{
"firstname": "Greg",
"email": "greg@fake_email.com",
"hobby":
[
{
"hobbyName": "sport",
"isHobby": "true"
},
{
"hobbyName": "reading",
"isHobby": "true"
},
{
"hobbyName": "music",
"isHobby": "false"
}
]
};
*/
Accessing fields is done like in any other JS object (mainly because it
is “normal” JavaScript object), if we want to know if hobby “reading”
was checked then we would have to write:
/*
JSONstring.hobby[1].isHobby; // true
*/

Creating JavaScript Objects

Before we start, we will need something to work with. We will create HTML form with “validate” button, when someone clicks this button the whole proccess i described in the first paragraph will start. Also, despite JSON is a subset of JavaScript there are no built in function for converting JavaScript object into JSON string, so we will use already created class available at JSON homepage, the file is located here json2.js.

Here is the code for the HTML form, i think there is no need to explain it:
/*

</script>

&lt;html>
<head>/span></span>ditio.net jSon Tutorial<span style="color: rgb(0, 153, 0);"><span style="color: rgb(0, 0, 0); font-weight: bold;">
<script src="http://www.json.org/json2.js">
<script>
// JavaScript source code will be here
</head>
<body>
<form name="personal" action="" method="POST">
Name &ltinput type="text" name="firstname">
<br>
Email <input type="text" name="email">
<br>
Hobby <input type="checkbox" name="hobby" value="sport">
Sport <input type="checkbox" name="hobby" value="reading">
Reading <input type="checkbox" name="hobby" value="music">
Music <input type="button" name="valid" value="Validate" onclick="validate()">
</form>
</body>
</html>
*/
After clicking “validate” button validate() function will be called, we need to add it, in head section for example:
/*
function validate()
{
var p = document.forms['personal'];

var JSONObject = new Object;
JSONObject.firstname = p['firstname'].value;
JSONObject.email = p['email'].value;
JSONObject.hobby = new Array;

for(var i=0; i<3; i++)
{
JSONObject.hobby[i] = new Object;
JSONObject.hobby[i].hobbyName = p['hobby'][i].value;
JSONObject.hobby[i].isHobby = p['hobby'][i].checked;
}

JSONstring = JSON.stringify(JSONObject);
runAjax(JSONstring);

}
*/

Code is quite easy to understand. First i assign whole form to variable p just to make further access to this form data easier. In next lines JavaScript object is created, as you can see it consists only from Object and Array data objects.

Note that this is completely the same object as in first listing of this tutorial, however different method was used to create it.

Sending JSON object to PHP with AJAX
/*

var request;

function runAjax(JSONstring)
{
// function returns "AJAX" object, depending on web browser
// this is not native JS function!
request = getHTTPObject();
request.onreadystatechange = sendData;
request.open("GET", "parser.php?json="+JSONstring, true);
request.send(null);
}

// function is executed when var request state changes
function sendData()
{
// if request object received response
if(request.readyState == 4)
{
// parser.php response
var JSONtext = request.responseText;
// convert received string to JavaScript object
var JSONobject = JSON.parse(JSONtext);

// notice how variables are used
var msg = "Number of errors: "+JSONobject.errorsNum+
"\n- "+JSONobject.error[0]+
"\n- "+JSONobject.error[1];

alert(msg);
}
}

*/
hat’s it we are half way there, now we need to create PHP script to handle AJAX request.

JSON and PHP

Decoding JSON string is very simple with PHP only one line of code is needed to parse string into object. Similary only one function is needed to encode PHP object or array into JSON string, look at the code:

/*php


// decode JSON string to PHP object
$decoded = json_decode($_GET['json']);

// do something with data here

// create response object
$json = array();
$json['errorsNum'] = 2;
$json['error'] = array();
$json['error'][] = 'Wrong email!';
$json['error'][] = 'Wrong hobby!';

// encode array $json to JSON string
$encoded = json_encode($json);

// send response back to index.html
// and end script execution
die($encoded);

*/
It is also interesting what is inside $decode variable
stdClass Object
(
[firstname] => fgfg
[email] =>
[hobby] => Array
(
[0] => stdClass Object
(
[hobbyName] => sport
[isHobby] => 1
)

[1] => stdClass Object
(
[hobbyName] => reading
[isHobby] =>
)

[2] => stdClass Object
(
[hobbyName] => music
[isHobby] =>
)

)
)

PHP finished execution, then “request” object status in JavaScript is now equal to 4. Response text (in sendData() function) will be parsed with JSON class to object and used to display message on the screen. Note that instead of using JSON.parse() we could use JavaScriipt eval() function.

Conclusion

This tutorial was intended to introduce you to JSON, and i wanted to make this tutorial as clear as possible so i intentionally used the simplest methods to achieve my goal. However this tutorial wouldn’t be complete if i wouldn’t give you further resources from which you can learn more.

First you should check out is Zend_Json class (a part of Zend Framework), it has the same functionality as json_decode() and json_decode(), but can handle more complicated JSON strings then those two functions.

Second is json.org home of JSON, check especially this tutorial, it has got great examples of more advanced JSON class usage.
courtsy: http://ditio.net

Beyond Spot-Checking: Why LLM Applications Require Specialized Evaluation

  images generated by meta ai Building applications with Large Language Models (LLMs) feels deceptively fast at first. A single engineer can...