Search code examples
phpjavascriptjsonjsonpjquery-callback

trouble to update or edit the json file using php


index.json

myjsoncallback([{"ProductID":1,"ProductName":"Chai","UnitPrice":18,"UnitsInStock":39,"Discontinued":false}])

Php Code :

$string = file_get_contents("../index.json");

$string = utf8_encode($string);

$json_data = json_decode($string, true);

echo $json_data;

$i=count($json_data);

$json_data[$i] = array('ProductID'=>$fileName,'ProductName'=>$name,'ptext'=>$message,'Discontinued'=>false);

$fp = fopen('../index.json', 'a');

fwrite($fp, json_encode($json_data));

fclose($fp);

I want to write data in jsone file with jsonpcallback.


Solution

  • You can't use json_decode() if your file contains JSONP data. If you want to handle JSON data with PHP you have to remove the callback form JSONP and just encode/decode JSON objects.