Web Services and PHP

PHP How To

Web Services are typically application programming interfaces (APIs) or web APIs that are accessed via Hypertext Transfer Protocol (HTTP) and executed on a remote system hosting the requested services.

Really Simple Syndication

RSS offers a formalized means for encapsulating a web site’s content within an XML-based structure, known as a feed. It is based on the premise that most site information shares a similar format, regardless of topic. 

For example, although sports, weather, and theater are dissimilar topics, the news items published under each share a similar structure: a title, an author, a publication date, a URL, and a description.

SimpleXML

A number of SimpleXML functions are available for loading and parsing the XML document.

Loading XML from File

The simplexml_load_file() function loads an XML file into an object.

$xml = simplexml_load_file("books.xml");
var_dump($xml);

If a problem is encountered loading the file, FALSE is returned.  

Loading XML from a String

If the XML document is stored in a variable, you can use the simplexml_load_string() function to read it into the object. This function is identical in purpose to simplexml_load_file(), except that the input parameter is expected in the form of a string rather than a file name.

Learning More About an Element

XML attributes provide additional information about an XML element. You can use the attributes() method to retrieve these attributes. For example,

echo $xml->book[2]->author->attributes();

Learning About a Node's Children 

You can use the children() method if you are interested only in a particular node's children.

Using XPath to Retrieve Node Information

XPath is a W3C standard that offers path-based syntax for identifying XML nodes. SimpleXML offers a method called xpath() for doing so. For example,

$authors = $xml->xpath("/library/book/author");

XPath also offers a set of functions for selectively retrieving nodes based on value. For example,

$book = $xml->xpath("/library/book[author='Ernest Hemingway']");