-
Notifications
You must be signed in to change notification settings - Fork 159
JSON
Dmitriy Zayceff edited this page May 31, 2015
·
3 revisions
To parse and format objects, arrays and primitives as JSON, you can use the php\format\JsonProcessor
class instead of json_encode
and json_decode
. JPHP supports these php functions, add the jphp-zend-ext
extension in your project to use them. To use the json class, you should add the jphp-json-ext
extension.
use php\format\JsonProcessor;
$json = new JsonProcessor(JsonProcessor::DESERIALIZE_AS_ARRAYS);
$result = $json->parse('{"x": 10, "y": 20}');
var_dump($result); // array [x => 10, y => 20]
$jsonFile = Stream::of('path/to/file.json');
try {
$result = $json->parse($jsonFile);
} finally {
$jsonFile->close();
}
Add the
jphp-http-ext
extension to use http and ftp sterams.
$jsonUrl = Stream:of('http://example.com/api/get.json');
try {
$result = $json->parse($jsonUrl);
} finally {
$jsonUrl->close();
}
$point = ['x' => 10, 'y' => 20];
$jsonString = $json->format($point);
echo $jsonString;
Use the jphp streams!
$point = ['x' => 10, 'y' => 20];
$output = Stream::of('path/to/file.json', 'w+'); // write mode.
try {
$json->formatTo($point, $output);
} finally {
$output->close();
}
$json = new JsonProcessor(JsonProcessor::SERIALIZE_PRETTY_PRINT);
// ...
JPHP Group 2015