Webbie Webbie - 6 months ago 11
PHP Question

Json Decode returning NULL

I am trying to decode json into array in PHP.But My json is like

string(307) " string(290) "{"id":"1","name":"test name","rowno":"0","note":"test notes","created_date":"2016-05-01","updated_date":"2016-05-12 05:08:05"}" "


string within a string!!
How to convert it into array.

Answer

This looks like you're trying to decode (or trying to output) the data with var_dump(). That isn't the function you require; what you require is json_decode():

$data = json_decode($json);

If that isn't the issue, and you're actually receiving the data as above then you'll have to strip it out - most likely using a regex like the following:

$s = 'string(307) " string(290) "{"id":"1","name":"test name","rowno":"0","note":"test notes","created_date":"2016-05-01","updated_date":"2016-05-12 05:08:05"}" "';

preg_match('/\{(.*)\}/', $s, $matches);

print_r($matches);

Which would return your json:

Array
(
    [0] => {"id":"1","name":"test name","rowno":"0","note":"test notes","created_date":"2016-05-01","updated_date":"2016-05-12 05:08:05"}
    [1] => "id":"1","name":"test name","rowno":"0","note":"test notes","created_date":"2016-05-01","updated_date":"2016-05-12 05:08:05"
)

Thus allowing you to decode it properly within $matches.

Regex is a beast to me so I'll try explain as best as possible what the expression is doing:

  • \{ matches the first open {
  • (.*) matches any character inbetween
  • \} matches the closing }