Monday, 31 March 2014

Using PHP to extract the JSON from a callback

This is of no benefit to anyone else but me as I get sick of having to re-invent the wheel every time I need to extract data from a callback - if it works for you then cool, if not then have a tinker and improve it. It's cobbled together from all sorts of different places and is a replacement for something I did before.

    $str = preg_replace("/\/\*[\s\S]*?\*\//", '',$str);
    $str = str_replace(PHP_EOL, '', $str);
    preg_match('/callback\(([^\)]*)\)/', $str, $matches);
    $str = $matches[1];

Just came across a situation where the JSON wasn't correctly formatted (i.e. the keys in key:value pairs wasn't enclosed with quotes). To correct this so that I could use PHPs json_decode I added these two lines:

$str = preg_replace('([a-zA-Z]+:)', '"$0":', $str);
$str = str_replace(':":', '":', $str);

No comments:

Post a Comment