Skip to content

Instantly share code, notes, and snippets.

@faejr
Created April 19, 2018 09:22
Show Gist options
  • Save faejr/4d91870fe8b55185f7114cbf5649dd24 to your computer and use it in GitHub Desktop.
Save faejr/4d91870fe8b55185f7114cbf5649dd24 to your computer and use it in GitHub Desktop.
<?php
// Gets indiivudal objects from a json string
// By checking for opening and closing brackets
// While ensuring they're all the same size
// - Daniel L. 2017-12-14
function getObject($stream) {
$openbrackets = 0;
$closedbrackets = 0;
$instr = false;
$startPos = 0;
$endPos = 0;
// Read only while we haven't reached end of line
while(!feof($stream)) {
// Get single character in stream
switch(fgetc($stream)) {
// Ensure that we're not inside a string
case '"':
$instr = !$instr;
break;
case '{':
if($instr) { break; } // Don't count if we're inside a string
// If this is our first open bracket
// Set start position of the object
if($openbrackets == 0) { $startPos = ftell($stream)-1; }
$openbrackets++;
break;
case '}':
if($instr) { break; } // Don't count if we're inside a string
$closedbrackets++;
break;
}
// Check if we have as many open as closed brackets (but not 0)
if($openbrackets == $closedbrackets && $openbrackets != 0) {
// Get end position
$endPos = ftell($stream);
// Return object string
return stream_get_contents($stream, $endPos-$startPos, $startPos);
}
}
// End of stream has been reached and no object was found
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment