Convert a PHP array to a valid JSON string for use in Javascript

Convert a PHP array to a valid JSON string for use in Javascript

Convert a PHP indexed array, associative array or multi-dimensional array into a valid JSON string that can then be used for processing in Javascript


Javascript object notation (JSON) is used as a standardized way to exchange and store data. Data can be formatted as a valid JSON string and then parsed into a

Javascript object

using built in Javascript functions. It is a great way of moving a lot of data from the server-side to the client side (or client to server) while still being easily able to understand and organize is once it has been transmitted especial when making use of

AJAX techniques

.


Converting your PHP array into a valid JSON string


To convert a PHP array into a JSON string, you can make use of the built in function json_encode(). This function takes an array as an argument and outputs a valid JSON string that can then be used in Javascript.


Converting an

associative array

into a JSON string (example):


$testArr = array( "item1" => 1, "item2" => 2, "item3" => 3);     
echo( json_encode( $testArr ) );

This will output the following JSON string:


{"item1":1,"item2":2,"item3":3}     

This string can now be used in Javascript.


As another example, let's create a more complicated

multi-dimensional array

and convert it into a JSON string:


$testArr = array();     
for($i = 0; $i < 3; $i++){     
    $testArr[ "item" . $i ] = array( "item1" => $i + 1, "item2" => $i + 2, "item3" => $i + 3 );     
}     
echo( json_encode( $testArr ) );

This will output the following JSON string:


{"item0":{"item1":1,"item2":2,"item3":3},"item1":{"item1":2,"item2":3,"item3":4},"item2":{"item1":3,"item2":4,"item3":5}}     


You can also include regular

indexed arrays

into your array to be encoded:


$testArr = array( "arr1" => array( 1, 2, 3 ), "arr2" => array( 4, 5, 6 ) );     
echo( json_encode( $testArr ) );

This will output the following JSON string:


{"arr1":[1,2,3],"arr2":[4,5,6]}   


Converting your JSON string into a Javascript object


Once you have acquired your JSON string in Javascript sent from the server through PHP, you can use the JSON.parse() method to convert it into a

Javascript object

from which you can easily access your data.


The JSON.parse() method takes a string as an argument, this string must be a valid JSON string or it will throw an exception. It will return a Javascript object that can then be stored in a variable.


As an example, say we had the following valid JSON string acquired from the server through PHP:


{"item1":1,"item2":2,"item3":3}

To convert it into a Javascript object, we'll use the JSON.parse() method and store the result in a variable from which we'll access the data.


var jsonString = '{"item1":1,"item2":2,"item3":3}'; 
 
var obj = JSON.parse( jsonString ); 
 
alert( obj.item1 + " " + obj.item2 + " " + obj.item3 ); 
 

This will output the following:


1 2 3 


Full example with PHP and Javascript


For this example we'll be creating an associative array in PHP which will be converted into a JSON string, to acquire the string in Javascript we'll use an

XMLHttpRequest object to asynchronously request the PHP file

and fetch the output (which will be the JSON string).


test.php:


$testArr = array( "item1" => 1, "item2" => 2, "item3" => 3);     
echo( json_encode( $testArr ) );


Javascript:


var xmlhttp = new XMLHttpRequest(); 
xmlhttp.onreadystatechange = function(){ 
    if ( xmlhttp.readyState === 4 && xmlhttp.status === 200 ) { 
        var response = xmlhttp.responseText; 
         
        var obj = JSON.parse( response ); 
        // process your object here 
    } 
} 
xmlhttp.open( "GET", "test.php", true ); 
xmlhttp.send(); 



Christopher Thornton@Instructobit 6 years ago
or