tags:

views:

937

answers:

4

Hi,

How to execute a XQuery in PHP? Can you give me an example?

Thank you.

A: 

Did you have a look at http://www.pecl.php.net/package/Zorba ?

Dominik
Dude! Compiling just for executing a simple query?! Sounds like rocket science here... nothing more simple?
abernier
A: 

pear package: http://www.pecl.php.net/package/Zorba zorba documentation: http://www.zorba-xquery.com/

zorba docs provide a simple example:

//Include for the Object-Oriented API
require ‘zorba_api.php’;

//Initialization of Zorba store
$store = InMemoryStore::getInstance();
//Initialization of Zorba
$zorba = Zorba::getInstance($store);

$xquery = <<< EOT
let $message := ‘Hello World!’
return
<results>
   <message>{$message}</message>
</results>
EOT;

//Compile the query
$lQuery = $zorba->compileQuery($xquery);
//Run the query…
echo $lQuery->execute();
//…and destroy it
$lQuery->destroy();

//Shutdown of Zorba
$zorba->shutdown();
//Shutdown of Zorba store
InMemoryStore::shutdown($store);
netricate
Same comment as for Dominik (http://stackoverflow.com/questions/2211743/execute-a-xquery-with-php#comment-2163837). Really, nothing more simple?
abernier
+2  A: 

PHP does not have any native or common XML parsers that support XQuery (If I'm wrong, someone let me know). It does however have two pretty standard extensions that handle XPath queries.

I personally think simplexml is the better of the two. You would simply use:

$xml = new simplexml($some_xml_string);
$xpath_results = $xml -> Xpath("//a/b");

And then loop through the results.

The extensive DOM class supports Xpath queries as well. The only real advantage, as far as I see it, to using DOM is that the results can be modified or deleted straight out of the larger XML object.

Good luck.

Anthony
XPath isn't the same as XQuery.
VolkerK
A: 

its also posible with DOMDocument and DOMXPath $doc = new DOMDocument(); $doc->loadXML(file_get_contents('http://some')); $xpd = new DOMXPath($doc); false&&$node = new DOMElement();//this is for my IDE to have intellysense

$result = $xpd->query('//a/b');
foreach($result as $node){
    echo $node->nodeName.'<br />';
}