Passing Multidimensional arrays between two servers

For a long time I was using JSONP to accomplish this, until I figured out a nifty function called json_encode() and of course it’s sister function json_decode().

The key here is to combine them with ob_start() function which allows you to capture raw output and dump it into a variable.

here’s how it works:

on remote server test.php file:

$array = array('hello','world','!');
$jsonString = json_encode($array);
echo $jsonString;

then what you want to do on the application server is include the remote file like this:

ob_start();
include_once('http://remoteserverdomain.com/test.php');
$string = ob_get_contents();
ob_end_clean();
$newArray = json_decode($string);

and there you have it. $newArray has the data you are looking for. now this works on any depth array, the only issue (that i have found anyway) is if your server is configured to not allow remote includes; an easy fix in php.ini though. I have found this way to be a lot easier to work with and generally more secure than using JSONP to pass the data.