May 312012
 
Article PHP

(leer este artículo en español)

In a previous post we explained the characteristics of the JSON format. Using JSON, complex data structures can be saved in a plain text file, readable by a person.

In this post we will show how to save and read a JSON-formatted data file from a PHP script.

We will use as an example a file named “data.json” with the following contents:

{
"boss":
    {
        "Name" : "John",
        "Age": 28,
        "Hobbies": ["Music", "Movies", "Tennis"],
        "Residence": "Birmingham"
    },
"employees":
    [
        {
            "Name" : "Hellen",
            "Age": 26,
            "Hobbies": ["Movies", "Tennis"],
            "Residence": "Birmingham"
        },
        {
            "Name" : "Richard",
            "Age": 31,
            "Hobbies": ["Football"],
            "Residence": "Birmingham"
        }
    ]
}

PHP 5.4

The PHP script below reads a JSON file, modifies the value of one of the elements in the data structure read, and writes the modified data structure to another file:

<?php
// Read the file contents into a string variable,
// and parse the string into a data structure
$str_data = file_get_contents("data.json");
$data = json_decode($str_data,true);

echo "Boss hobbies: ".$data["boss"]["Hobbies"][0]."n";

// Modify the value, and write the structure to a file "data_out.json"
//
$data["boss"]["Hobbies"][0] = "Swimming";

$fh = fopen("data_out.json", 'w')
      or die("Error opening output file");
fwrite($fh, json_encode($data,JSON_UNESCAPED_UNICODE));
fclose($fh);

In line 4 the file contents are read and assigned as a string to the  $str_data variable.

In line 5 the  ‘json_decode’ method is called. This method parses the string into a PHP data structure. Both the associative arrays (Enclosed in curly braces ‘{‘ and ‘}’ in the input file ), and the ‘standard’ arrays (Enclosed in square brackets ‘[‘ and ‘]’ in the input file) are converted into PHP arrays.

In line 7 we see how one of the values inside the data structure can be accessed, by navigating the array tree.

In line 10 the value is modified, and in the next lines the ‘json_encode’ method is used to convert the data structure back into a JSON-formatted string, which is then written into an output file ‘data_out.json’.

As we can see, the call to ‘json_encode’, specifies the ‘JSON_UNESCAPED_UNICODE’ flag. This flag is available since PHP 5.4, and is relevant if we are working with data that includes strings with characteres outside de ASCII set, normally found in most languages other than english.

Without this flag, json_encode converts any non-ASCII character found into unicode escape sequences. For instance, the string ‘Música’ would be written as “Mu00fasica”. Although this is a valid unicode text (and can be read back by json_decode into a PHP variable), it is not well suited to be read by a person. The flag JSON_UNESCAPED_UNICODE ensures that these characters are converted into their equivalent UTF8-encoded character. In this way, any text editor supporting UTF-8 encoding will display the string as “Música”.

PHP versions prior to 5.4

If the PHP version we are using is earlier than 5.4, we can’t use the JSON_UNESCAPED_UNICODE flag.

For this reason, if working with unicode escape sequences is not an option, we must write our own conversion routine to convert from unicode escape sequences to UTF-8. The new script would be like this:

<?php
// Read the file contents into a string variable,
// and parse the string into a data structure
$str_data = file_get_contents("data.json");
$data = json_decode($str_data,true);

echo "Boss hobbies: ".$data["boss"]["Hobbies"][0]."n";

// Modify the value, and write the structure to a file "data_out.json"
//
$data["boss"]["Hobbies"][0] = "Swimming";

$fh = fopen("data_out.json", 'w')
      or die("Error opening output file");
fwrite($fh, unescape(json_encode($data)));
fclose($fh);

function code2utf($num){
    if($num<128)
        return chr($num);
    if($num<1024)
          return chr(($num>>6)+192).chr(($num&63)+128);
    if($num<32768)
        return chr(($num>>12)+224).chr((($num>>6)&63)+128)
              .chr(($num&63)+128);
    if($num<2097152)
        return chr(($num>>18)+240).chr((($num>>12)&63)+128)
                .chr((($num>>6)&63)+128).chr(($num&63)+128);
    return '';
}

function unescape($strIn, $iconv_to = 'UTF-8') {
    $strOut = '';
    $iPos = 0;
    $len = strlen ($strIn);
    while ($iPos < $len) {
        $charAt = substr ($strIn, $iPos, 1);
        if ($charAt == '\') {
            $iPos++;
            $charAt = substr ($strIn, $iPos, 1);
            if ($charAt == 'u') {
                // Unicode character
                $iPos++;
                $unicodeHexVal = substr ($strIn, $iPos, 4);
                $unicode = hexdec ($unicodeHexVal);
                $strOut .= code2utf($unicode);
                $iPos += 4;
            }
            else {
                // Escaped ascii character
                $hexVal = substr ($strIn, $iPos, 2);
                if (hexdec($hexVal) > 127) {
                    // Convert to Unicode
                    $strOut .= code2utf(hexdec ($hexVal));
                }
                else {
                    $strOut .= chr (hexdec ($hexVal));
                }
                $iPos += 2;
            }
        }
        else {
            $strOut .= $charAt;
            $iPos++;
        }
    }
    if ($iconv_to != "UTF-8") {
        $strOut = iconv("UTF-8", $iconv_to, $strOut);
    }
    return $strOut;
}
?>

 

 Posted by at 4:24 pm

  One Response to “How to read and write JSON files in PHP”

 Leave a Reply

(required)

(required)


2 + = six