Search code examples
phpajaxjsonencodingserver-side

File saving to server as invalid JSON


I am saving json to the server using a PHP script as follows:

<?php

$json = $_POST['json'];
$file = fopen('jsonfile.json', 'wb');
fwrite($file, $json);
fclose($file);


?>

The script reads in the existing jsonfile.json file and writes the new json to it...then saves it to the server. But this results in invalid json. I know that the actual json is indeed valid because if I use document.write() to show the json in the browser, and copy/paste that json to a validator it is perfect. But the actual json in the file that has been written to the server is invalid and therefore unuseable to any program.

I am assumiming it has something to so with encoding. I have tried using headers that enforce UTF-8 in the php script but to no avail.

The json looks like this:

{  
   "name":"First Name",
   "children":[  
      {  
         "name":"Second Name",
         "children":[  
            {  
               "name":"Third Name",
               "children":[  
                  { 

and so on....

Again, this IS valid JSON as when using document.write() and pasting into a validator it is fine. If I were to show the json in the file that has been written to the server it would look identical. It's like there is some hidden formatting we don't see not allowing a validator to pass it and obviously not allowing programs to run it.

Here is the AJAX to POST the json to the php script:

$.ajax({
         url: 'json.php',
         data: {
         json: theJsonBeingWritten
         },
         dataType: "json",
         type: "POST"
         });

This sucessfully writes the file to the server, but something is wrong with the format/characters(?)

I have also tried adding processData: false to the AJAX section in order to stop conversion into whatever PHP is turning my json into. I also tried using JSON.stringify({json: theJsonBeingWritten}) to the data: section of ajax but to no avail. I have also tried using $.post( "json.php", theJsonBeingWritten ); instead of $.ajax but this also did not work. I have also set the content-type to Content-type: application/json".


Solution

  • So I was finally able to discover the sneaky little symbols in the JSON. These did not appear in any text editor or hex-editor or validator. Only until seeing the JSON from the raw URL did the circumflex symbols appear. Something in the PHP fwrite() function was forcing these in despite any attempts at forcing encoding. Anyway, using the following to remove the characters from the json in the PHP script prior to using fwrite() did the trick:

    $string = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $string);