从数据中提取JSON数组

I am requesting data from another website and expecting a clean json array in return.

However I am getting this instead:

<pre></pre>{"Status":"Success","Result":1}

which won't parse with json_decode();.

How do I extract the JSON array out of this data so I can parse it?

Note: I am not in control of the code I am requesting the data from.

try this

$output_array = array();

$badstr = '<pre></pre>{"Status":"Success","Result":1}';

preg_match("/{.*}/", $badstr, $output_array);

in $output_array[0] you have your json string.

Assuming that <pre></pre> is constant, then just a simple substring operation:

$badstr = '<pre></pre>{"Status":"Success","Result":1}';
$goodstr = substr($badstr, 11);

But you really should yell at the server admins for sending out bad json in the first place. There's no excuse for this kind of thing. It's probably some debug code they forgot to take out.

If you want it to work both now, and once the issue will be fixed, you can do this:

$result = '<pre></pre>{"Status":"Success","Result":1}';

if (strpos($result ,'<pre>') !== false) 
{
    $array = json_decode(substr($result , 11));
}
else
{
    $array = json_decode($result);
}

How about simply string replace?

Like so:

$json_string = '<pre></pre>{"Status":"Success","Result":1}';

$json = str_replace("<pre></pre>", "", $json_string);

echo $json;

Output:

{"Status":"Success","Result":1}

If you don't expect any html tags in your output, you can also use strip_tags():

$not_json = '<pre></pre>{"Status":"Success","Result":1}';
$json_string = strip_tags($json);
$result = json_decode($json_string);

Only remove <pre></pre>, only if it's the first thing:

$response = preg_replace('#^<pre></pre>#', '', $response);