Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Input, output and serialization

A stream has a cursor. After writing JSON to a seekable stream, rewind before reading it back.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

fopen("php://memory", "w+"); rewind($stream);

A stream has a cursor. After writing JSON to a seekable stream, rewind before reading it back. JSON_THROW_ON_ERROR distinguishes invalid encoding or syntax from valid JSON null. Decoding with associative=true produces PHP arrays for JSON objects. Close resources after use.

$fp=fopen("php://memory","w+");fwrite($fp,json_encode(["sku"=>"007"],JSON_THROW_ON_ERROR));$atEnd=stream_get_contents($fp);rewind($fp);$row=json_decode(stream_get_contents($fp),true,512,JSON_THROW_ON_ERROR);fclose($fp);echo json_encode([$atEnd,$row["sku"]]);
$null=json_decode("null",true,512,JSON_THROW_ON_ERROR);try{json_decode("{",true,512,JSON_THROW_ON_ERROR);}catch(JsonException $e){echo "\n",json_encode([$null,get_class($e)]);}
["","007"]
[null,"JsonException"]

Examples

<?php
$fp=fopen("php://memory","w+");fwrite($fp,json_encode(["sku"=>"007"],JSON_THROW_ON_ERROR));$atEnd=stream_get_contents($fp);rewind($fp);$row=json_decode(stream_get_contents($fp),true,512,JSON_THROW_ON_ERROR);fclose($fp);echo json_encode([$atEnd,$row["sku"]]);
$null=json_decode("null",true,512,JSON_THROW_ON_ERROR);try{json_decode("{",true,512,JSON_THROW_ON_ERROR);}catch(JsonException $e){echo "\n",json_encode([$null,get_class($e)]);}

Result

["","007"]
[null,"JsonException"]

Sources