This article is more than 1 year old
Harness XML with PHP 5 extensions
A time to query
Parse the XML
To parse the XML document catalog.xml
create a PHP file, parseXML.php
. Create a DOMDocument
object. Load the example XML document using load(String xmlFile)
. Another function loadXML(string xmlDocument)
may be used to load an XML document from a String
.
$domDocument->load("file://C:/PHP/catalog.xml");
As an example, obtain all the title
nodes in the XML document using getElementsByTagName(string tagName)
. Iterate over the node list and output the title
elements' values.
$titleNodeList=$domDocument->getElementsByTagName("title"); for($i=0; $I<$titleNodeList->length;$i++) { echo $titleNodeList->item($i)->nodeValue; print "<br/>\n"; }
The output from the PHP script is shown below.
The Java XPath API JAXP validation
Navigate XML with XPath
To navigate the XML document using XPath create a PHP script, xpath.php
. Create a DOMDocument
object and load the example XML document with load(string filename)
.
The DOMXPath
class is used to evaluate an XPath expression in the context of an XML document node. Create a DOMXPath
object.
$domXPath=new DOMXPath($domDocument);
XPath expressions may be evaluated with query()
. Parameter of type DOMNode
is optional in query()
. By default the context node is the root element. As an example, retrieve the values of all the title
elements.
$titles=$domXPath->query("/catalog/journal/article/title");
The query()
returns a DOMNodeList
. Iterate over the DOMNodeList
to output the values of the title
elements.
foreach ($titles as $title) { echo 'Title: ', $title->firstChild->nodeValue; print "<br/>\n"; }
The output from the xpath.php
script is shown below.
Title: The Java XPath API Title: JAXP validation
Validate your XML
In this section we validate the example document with an XML schema, catalog.xsd
. The schema validation functions, schemaValidate(string filename)
and schemaValidateSource(string schema)
, return a boolean value indicating if an XML document is valid. Limitations of the schema validation functions are that only one schema may be specified for validation and that the detail of the validation error is not output.