This article is more than 1 year old

Harness XML with PHP 5 extensions

A time to query

Create a PHP script, validateXML.php. Create a DOMDocument object and load the XML document. Validate the XML document with the XML schema using schemaValidate().

$isValid=$domDocument->schemaValidate("file://C:/PHP/catalog.xsd");

The output from the PHP script is as follows.

XML Document is valid

Query XML with SimpleXML

PHP 5 provides the SimpleXML extension to select XML document nodes and node values with property selectors and array iterators. To select nodes and output node values in the XML document using the SimpleXML extension create a PHP script, simpleXML.php. The SimpleXML extension provides functions simplexml_load_file(string filename) and simplexml_load_string(string xmlDocument) to load an XML document from a file or a string.

$simplexml=simplexml_load_file("file://C:/PHP/catalog.xml");

The simplexml_load_file() converts the XML document to an object of type SimpleXMLElement, and returns the root element in the XML document. As an example, output the value of the title element of the article in the first journal element.

print $simplexml->journal->article->title;

As the $simplexml object represents the root element in the XML document parsed, the value of the title attribute in the root element, catalog, is obtained as shown below.

print   $simplexml['title'];

The attributes of an element may be output using attributes(). For example, obtain the attributes in the root element.

$attributes=$simplexml->attributes();

Output the publisher attribute.

print $attributes['publisher'];

The output is shown below.

The Java XPath API
XML Zone
IBM developerWorks
Next page: Transform XML

More about

TIP US OFF

Send us news


Other stories you might like