Exctracts JSON data recursively from string and array
<?php
function extractData($source, &$output) {
$sourceType = gettype($source);
echo "Trying to determine source type..$sourceType\n";
echo "Extract data:\n";
switch($sourceType){
case "array":
echo "Goin' to iterate an array..\n";
foreach($source as $key => $value)
{
extractData($value, $output[$key]);
}
break;
case "string":
echo "Goin' to decode JSON from string..\n";
$decoded = extractJson($source);
if($decoded) {
echo "Decoded!\n";
extractData($decoded, $output);
}
else {
echo "Failed to decode JSON, output string.\n";
$output = $source;
}
break;
case "integer":
echo "Skip extraction, output value\n";
$output = $source;
break;
default:
echo "Failed to extract any data, undetermined type..$sourceType\n";
}
return;
}
function extractJson($string) {
$decoded = json_decode($string, true);
if (json_last_error() == JSON_ERROR_NONE) return $decoded;
else return null;
}
echo "Start:\n";
$output=[];
$source = file_get_contents(__DIR__."/DataRaw/json.json");
$extracted=extractData($source, $output);
print_r($output);