php test for data in json code example

Example 1: php check if json

function isJson($string) {
 json_decode($string);
 return (json_last_error() == JSON_ERROR_NONE);
}

Example 2: php return json data

header('Content-Type: application/json'); 

$colors = array("red","blue","green");
echo json_encode($colors);

Example 3: php is json

function is_json($input_line) {
    if(is_string($input_line)){
        preg_match('/^\{(\s+|\n+)*(\"(.*)(\n+|\s+)*)*\}$|^\[(\s+|\n+)*\{(\s+|\n+)*(\"(.*)(\n+|\s+)*)*\}(\s+|\n)*\]$/', $input_line, $output_array);
        if (  isset($output_array) || !empty($output_array)) {
            return true;
        }
    }
    return false;
    }