I've been playing a bit with BaseX the last couple of days - and very
excited about the product while doing so - but now I am having problems
outputting JSON from a PHP script.
I have this XQuery:
declare option output:method "json";
declare option output:json "format=jsonml";
<json type="object">
{
for $user in
collection("saveresult")//user[_id="1f2cda8f-a18a-44ba-8d17-73626d472306"]
return
<testResults>
<testId>{$user/test/_id}</testId>
<grade>{$user/user_info/user_grade}</grade>
</testResults>
}
</json>
In the BaseX GUI this yields:
["json", {"type":"object"},
["testResults",
["testId",
["_id",
"Bio-1"]],
["grade",
["user_grade",
"7"]]],
["testResults",
["testId",
["_id",
"Bio-2"]],
["grade",
["user_grade",
"1"]]]]
Which is what I expected after reading about the JSONML format. (Not too
happy with that format, but that's another story).
Running exactly the same XQuery form within a PHP script however yields
this:
<json type="object">
<testResults>
<testId>
<_id>Bio-1</_id>
</testId>
<grade>
<user_grade>7</user_grade>
</grade>
</testResults>
<testResults>
<testId>
<_id>Bio-2</_id>
</testId>
<grade>
<user_grade>1</user_grade>
</grade>
</testResults>
</json>
(script is attached; note that the $ signs have been escaped there so
that PHP will not try to evaluate them)
In other words, the result is being output as XML with an enclosing
<json> root tag, not as JSON.
What is happening here? And how can I have BaseX return JSON from PHP?
Paul Swennenhuis
<?php
/*
* This example shows how queries can be executed in an iterative manner.
* Documentation: http://basex.org/api
*
* (C) BaseX Team 2005-11, BSD License
*/
include("BaseXClient.php");
try {
// create session
$session = new Session("localhost", 1984, "admin", "a33445");
try {
// create query instance
// make sure to escape $ signs!
$input = <<<XQ
declare option output:json "format=jsonml";
<json type="object">
{
for \$user in
collection("saveresult")//user[_id="1f2cda8f-a18a-44ba-8d17-73626d472306"]
return
<testResult>
<testId>{\$user/test/_id}</testId>
<grade>{\$user/user_info/user_grade}</grade>
</testResult>
}
</json>
XQ;
//print $input;
$query = $session->query($input);
// bind variable
//$query->bind("$name", "number");
print $query->execute()."\n";
// close query instance
$query->close();
} catch (Exception $e) {
// print exception
print $e->getMessage();
}
// close session
$session->close();
} catch (Exception $e) {
// print exception
print $e->getMessage();
}
?>