Read first only record from json file using PHP -
i have json file having content :
[{ "name" : "mak", "registration_code" : "registration code", "date" :"date", "time" : "time", "file_data" :{ "feature_0" : "0,0.956222737454317," } }, { "name" : "andy", "date" :"date", "time" : "time", "file_data" :{ "feature_0" : "0,0.956222737454317, " } }] right read first record using file_get_contents complete data , parsing array. want fetch first record without getting whole file content in memory using php. there way ?
many thanks, m.
this hack if know json structure. anyway }, may not occur in first record.
$first = explode("},", $json_string, 2)[0]; $first .= "}]"; $obj = json_decode($first)[0]; if not want read whole json file (adjust needs!):
$content = ""; $handle = fopen("json.file", "r"); if ($handle) { while (($line = fgets($handle)) !== false) { // nested objects have count occurrences of { , make sure closer first object if (strpos($line, '},') !== false) { break; } else { $content .= $line; } } fclose($handle); } // proceed lines read ... $content .= "}]"; $obj = json_decode($content)[0]; anway suggested here is not recommendable (in 99% of use cases). maybe have adapt code bit , not work minified json.
better parse whole file , go ahead.
Comments
Post a Comment