Dec
09
2008
0

XML: XPath

XPath (XML Path Language) is used to access and search XML documents, it is a query language for retrieving data from an XML document. XPath can be complex. SimpleXML uses xpath like such SimpleXMLElement::xpath(); if used on root element it will search the entire xml document or if used on a child it will search the entire child.

XPath reutns an array of SimpleXMLElment objects, here is an example of searching root and child

// Search the root element
$results = $library->xpath(/library/book/title’);
foreach ($results as $title){
	echo $title . "\n";
}
 
// Search the first child element
$results = $library->book[0]->xpath(’title’);
foreach ($results as $title){
	echo $title . "\n";
}
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • LinkedIn
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
Written by Adam in: 06. XML and Web Services |
Nov
27
2008
0

PHP5 Soap: Creating Server

As SoapClient makes it easy to interprate Web Service, SoapServer will make it easy to provide Soap Services. To create a SOAP server you simply start with a class that contains methods (functions) that you wish to allow other computers to use.

Creating a Small SOAP Server

class MySoapServer{
	public function getMessage(){
		return ’Hello, World!’;
	}
	public function addNumbers($num1, $num2){
		return $num1 + $num2;
	}
}

The above is a class, this contains the methods that we want to let people use, so we are turning our server into a Hello World Calculator.

SOAP by default does not output in WDSL mode, this is tedious and you have to create your WSDL file manually. Its recommended to use WSDL as it gives your users the methods and data types available. The server prefers WSDL as it makes handling complex data simpler.

In this example we will operate in non-WSDL mode.

In the example bellow we inform SOAP that the class we went it to work with is MySoapServer (shown above):

$options = array(’uri’ => ’http://example.org/soap/server/’); //Define Soap Options
$server = new SoapServer(NULL, $options); //Start soapserver and provide it the options
$server->setClass(’MySoapServer’);//Tell Soap which Class to work with
$server->handle(); //process incoming requests

Useing our new SOAP Server

The followng code shows how a computer can interact with our SOAP server, you will notice how the client is able to access getMessage() and addNumbers():

//Define Options
$options = array(
’location’ => ’http://example.org/soap/server/server.php’,
’uri’ => ’http://example.org/soap/server/’
);
$client = new SoapClient(NULL, $options); //Create SOAP Class and give it Options
echo $client->getMessage() . "\n"; // This will output Hello WOrld
echo $client->addNumbers(3, 5) . "\n"; //This will output 8
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • LinkedIn
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
Written by Adam in: 06. XML and Web Services |
Nov
27
2008
0

PHP5 SOAP: Debugging

SoapClent allows us to debug messages sent and received. This is done by setting the trace option to 1 when instantiating SOAP. This gives us the SOAP headers and envelope body.

$client = new SoapClient('http://api.google.com/GoogleSearch.wsdl',array('trace' => 1));
$results = $client->doGoogleSearch(NULL, $query, 0, 10, FALSE, '',FALSE, '', '', '');
echo $client->__getLastRequestHeaders();
echo $client->__getLastRequest();

This will output the header requests of the file, followed by the envelope bodies.

POST /search/beta2 HTTP/1.1
Host: api.google.com
Connection: Keep-Alive
User-Agent: PHP SOAP 0.1
Content-Type: text/xml; charset=utf-8
SOAPAction: "urn:GoogleSearchAction"
Content-Length: 900
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns1="urn:GoogleSearch"
 
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<ns1:doGoogleSearch>
<key xsi:type="xsd:string">XXXXXXXXXX</key>
<q xsi:type="xsd:string">PHP: Hypertext Preprocessor</q>
<start xsi:type="xsd:int">0</start>
<maxResults xsi:type="xsd:int">10</maxResults>
<filter xsi:type="xsd:boolean">false</filter>
<restrict xsi:type="xsd:string"></restrict>
<safeSearch xsi:type="xsd:boolean">false</safeSearch>
<lr xsi:type="xsd:string"></lr>
<ie xsi:type="xsd:string"></ie>
<oe xsi:type="xsd:string"></oe>
</ns1:doGoogleSearch>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • LinkedIn
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
Written by Adam in: 06. XML and Web Services |
Nov
27
2008
0

PHP5 SOAP

SOAP Trivia: SOAP used to stand for Simple Object Access Protocol, but in SOAP 1.2 t was dropped and now SOAP means SOAP.

About SOAP

SOAP is anouther tool for communication between two systems, allowing you to define and exchange data types in request or responce. It is interlinked to XML as all messages are sent in a SOAP envelope that is an XML wrapper, but creating XML for this wrapper is tedious therefore PHP5 simplifies this process with its SOAP extension making use of Servers and Clients easy.

A SOAP Web service is defined by using a Web Service Description Language (WSDL, pronounced “whisdl”) document. This, in turn, is yet another XML document that describes the function calls made available by a Web service, as well as any specialized data types needed by it.

SOAP also supports Remote Procedure Call (RPC). this allows you to execute a procedure on another address space (a different local computer). RPC may be referred to as remote invocation or remote method invocation.

Using SOAP Web Services

As we mentioned SOAP is used for communication between two computers, in the example bellow we will talk to google. SoapClient gives us such ability, the first step is to tell SOAP the path to a WSDL fle.

<?php
try{
	$client = new SoapClient('http://api.google.com/GoogleSearch.wsdl');
	$results = $client->doGoogleSearch($key, $query, 0, 10, FALSE, '',FALSE, '', '', '');
	foreach ($results->resultElements as $result){
		echo '<a href="'.htmlentities($result->URL).'">';
		echo htmlentities($result->title, ENT_COMPAT, 'UTF-8');
//		echo htmlentities($result->title);
		echo '</a><br/>';
	}
}
 
catch (SoapFault $e){
	echo $e->getMessage();
}
?>

This creates a new SOAP client using Google’s WSDL file. SoapClient uses theWSDL file to construct an object mapped to the methods defined by the web service; thus, $client will now provide the methods doGetCachedPage(), doSpellingSuggestion(), and doGoogleSearch(). In our example, the script invokes the doGoogleSearch() method to return a list of search results. If SoapClient encounters any problems, it will throw an exception, which we can trap as explained in the Object-oriented Programming in PHP chapter). The constructor of the SOAPClient class also accepts, as an optional second parameter, an array of options that can alter its behaviour; for example, you can change the way data is encoded, or whether the entire SOAP exchange is to be compressed, and so on.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • LinkedIn
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
Written by Adam in: 06. XML and Web Services |
Nov
27
2008
0

Web Services

Define: Web Services

provide a standard means of interoperating between different software applications, running on a variety of platforms and/or frameworks
- Quote W3C

In other words Web Services is a term for allowing programming language A on one system, to pass data effectively to Programming Language Y on a different system.
Today we have three popular types of web services:
- XML-RPC
- SOAP
- REST
As expected PHP 5 contained tools to use with XML it also has 5 tools suited for SOAP and REST.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • LinkedIn
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
Written by Adam in: 06. XML and Web Services |
Nov
27
2008
0

XML Dom: Use with SimpleXML

You can interchange data with SimpleXML and DOM, this allows us to take advantage of each systems strengths. We can import SimpleXML objects to DOM by using:
dom_import_simplexml();

$sxml = simplexml_load_file(’library.xml’); //Import libary.xml to simplexml
$node = dom_import_simplexml($sxml); //Convert data from SimpleXML to Dom
 
$dom = new DomDocument(); //Create dom Object
$dom->importNode($node, true); //Import simplexml data to Dom
$dom->appendChild($node);

The opporsite is obviosy possible, taking DOM data to SimpleXML:

$dom = new DOMDocument(); // Start DOM object
$dom->load(’library.xml’); // Import XML to Dom
$sxe = simplexml_import_dom($dom); //Import DOM to SimpleXML $sxe
echo $sxe->book[0]->title;//Print out the first books title
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • LinkedIn
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
Written by Adam in: 06. XML and Web Services |
Nov
27
2008
0

XML Dom: Remove Data

XML Dom: Removing Data

Their are three types of data you may want to delete from a XML document:
attributes
elements
CData
PHP5 Dom has different methods for each of these tasks:
DomNode::removeAttribute();
DomNode::removeChild();
DomCharacterData::DeleteData();

//Create String XML Document
$xml = <<<XML
<xml>
<text type="misc">some text here</text>
<text type="misc">some more text here</text>
<text type="misc">yet more text here</text>
</xml>
XML;
 
$dom = new DOMDocument(); //Create DOM Object
$dom->loadXML($xml); //Load XML String to Dom Object
 
$xpath = new DomXpath($dom);//Start xpath
$result = $xpath->query("//text"); //fetch all <text xml dat
 
$result->item(0)->parentNode->removeChild($result->item(0)); // Will remove the whole first set of XML data "some text here"
 
$result->item(1)->removeAttribute(’type’); // Remove type=""
$result = $xpath->query(’text(), $result->item(2));
$result->item(0)->deleteData(0, $result->item(0)->length);
echo $dom->saveXML();

In this example, we start by retrieving all of the text nodes from our document, then we remove the first one by accessing its parent and passing the former to DomNode::removeChild(). Next, we remove the type attribute from the second element using DomNode->removeAttribute(). Finally, using the third element,we use Xpath again to query for the corresponding text() node, passing in the third element as the context argument, and then delete the CDATA using DomCharacterData::deleteData(), passing in an offset of 0 and a count that is the same as the length of the CDATA node.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • LinkedIn
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
Written by Adam in: 06. XML and Web Services |
Nov
27
2008
0

XML Dom: Modifying Data

We can modify data using DOM and XPath, in this example bellow we will create a sample XML document and use UCWords to capitalise the first letter of the words in the XML Document.

$xml = <<<XML
<xml>
<text>some text here</text>
</xml>
XML;
$dom = new DOMDocument(); //Create dom Object
$dom->loadXML($xml); // Load XML from string above
$xpath = new DomXpath($dom); // Use xpath with dom
$node = $xpath->query("//text/text()")->item(0); // use xpath to get the data from xml
$node->data = ucwords($node->data); //capitalise the data, then set it back to the variable
echo $dom->saveXML();//Output XML to string

We can change the line ucwords($node->data); to anything allowing us to change the data completely, add a prefix, suffix, uncapitalised whatever you need to do to modify the data.
We can also use a loop, to capitalise all data in the xml document.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • LinkedIn
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
Written by Adam in: 06. XML and Web Services |
Nov
26
2008
1

XML Dom: Moving Data

The PHP5 Zend Certification required knowledge about manipulating XML useing DOM. In this section of the blog I will outline how to move/rearrange xml data using PHP5 Dom.

Dom does not have any specific methods of moving data, Instead we can use a mix of its other functions to get the desired result:
DomNode::appendChild();
DomNode::insertBefore();

Note that DomNode::insertAfter(); does not exist in PHP5.

insertBefore(newElement, referenceElement); as you can see the first perimeter is the new xml data that you wish to be in the document, the second perimeter is the reference, in other words which section of xml data do we need to insert it before.

appendChild(newElement);This only needs one parimiter which is the data that wants adding to the end of the xml document.
(more…)

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • LinkedIn
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
Written by Adam in: 06. XML and Web Services |
Nov
26
2008
1

XML Dom: Xpath Queries

xPath Queries are available in SimpleXML and DOM except the latter is more powerful.

$dom = new DomDocument(); //Create DOM Object
$dom->load("library.xml"); //Load External XML Document
$xpath = new DomXPath($dom); //Initiate XPath and passing domDocument object to it.
$xpath->registerNamespace("lib", "http://example.org/library"); //register only the namepsace we need
$result = $xpath->query("//lib:title/text()"); //query xml to return DomNodeLst object.
foreach ($result as $book) {
	echo $book->data;
}

The above code will search the libary.xml for the title of each book in the xml. It then echo’s the books title ($book->data) in a foreach loop to display them all.

A different method is to check the length of the returned data like such:

if ($result->length > 0) {
	// Random access
	$book = $result->item (0);
	echo $book->data;
	// Sequential access
	foreach ($result as $book) {
		echo $book->data;
	}
}

This checks the amount of returned book tites, if the value is greater than 0 it prints the first book title, then completes a foreach to output the rest.

As you can see XPath is very useful with XML Documents with use with SimpleXML and DOM. Its has similarities to regex searching and returning data.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • LinkedIn
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
Written by Adam in: 06. XML and Web Services |

WordPress Powered, Theme by TheBuckmaker.com | Add to Technorati Favorites. | RSS and Comments RSS