Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / PHP

Input, output e serializzazione

Uno stream ha una posizione. Dopo aver scritto JSON in uno stream riposizionabile usare rewind prima della lettura.

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

Sintassi

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

Uno stream ha una posizione. Dopo aver scritto JSON in uno stream riposizionabile usare rewind prima della lettura. JSON_THROW_ON_ERROR distingue errori di sintassi o codifica da null valido. associative=true decodifica gli oggetti JSON in array PHP. Chiudere la risorsa dopo l’uso.

$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"]

Esempi

<?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)]);}

Risultato

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

Fonti