test.php
This is a simple example that demonstrate how to use the Zorba XQuery Engine to create, compile, and execute queries.
<?php
require 'XQueryProcessor.php';
function omitXMLDecl($xml)
{
$xml = str_replace('<?xml version="1.0" encoding="UTF-8"?>', '', $xml);
$xml = trim($xml);
return $xml;
}
function assertEquality($test, $reference, $label)
{
$test = omitXMLDecl($test);
echo "=====================================\n";
var_dump($test);
var_dump($reference);
if($test != $reference) {
throw new Exception(
"Test "
. $label
. " failed. Result:\n"
. $test
. "\nDoesn't match reference:\n"
. $reference
);
}
}
$xquery = new XQueryProcessor();
$xquery->importQuery('1+1');
$result = $xquery->execute();
assertEquality($result, '2', "1+1");
$query = '
declare variable $foo as xs:string external;
declare variable $bar as xs:integer external;
declare variable $doc1 as document-node() external;
declare variable $doc2-str as xs:string external;
declare variable $doc2 as document-node() := parse-xml($doc2-str);
$foo, $bar, $doc1 , $doc2
';
$xquery->importQuery($query);
$xquery->setVariable("foo", "bar");
$xquery->setVariable("bar", 3);
$doc = simplexml_load_string('<root />');
$xquery->setVariable("doc1", $doc);
$doc = "<root />";
$xquery->setVariable("doc2-str", $doc);
$result = trim($xquery->execute());
assertEquality($result, "bar 3<root/><root/>", "Test PHP Types Mapping");
$xquery->importQuery("(1, 2, <foo bar='bar' />)");
$it = $xquery->getIterator();
foreach($it as $pos => $value) {
switch($pos) {
case 0:
assertEquality($value, "1", "Consume the item at position {$pos}");
break;
case 1:
assertEquality($value, "2", "Consume the item at position {$pos}");
break;
case 3:
assertEquality($value, '<foo bar="bar"/>', "Consume the item at position {$pos}");
break;
}
}
foreach($xquery as $pos => $value) {
switch($pos) {
case 0:
assertEquality($value, "1", "Consume the item at position {$pos}");
break;
case 1:
assertEquality($value, "2", "Consume the item at position {$pos}");
break;
case 3:
assertEquality($value, '<foo bar="bar"/>', "Consume the item at position {$pos}");
break;
}
}
$result = $xquery->execute();
assertEquality($result, "1 2<foo bar=\"bar\"/>", "Execute To URI");
$xquery->importQueryFromURI("/home/jenkins/.jenkins/ubuntu-remote-queue/jenkins-BuildZorbaUbuntu-462/source/zorba/build/swig/php/test.xq");
$result = $xquery->execute();
assertEquality($result, "2", "Test importQueryFromURI");
?>