A lot of web services provide you with some useful JSON formatted data in exchange for a few parameters or just some love, and this is a particularly simple and easy method to grab some of that JSON goodness for use in your own PHP page. In order to grab the data, we’ll first create a HTTP stream content where we’ll add the all important X-Request-With = XMLHttpRequest header that is used to identify requests as being AJAX requests. At this point you can add any parameters you wish to hit the web service with by adding them as an associative array and wrapping them in a http_build_query() call for the context content. The next step is to use the classic file_get_contents (this assumes your apache/PHP allows the use of the function to open URLs) to hit the target URL using the newly created context. This should work, resulting in a JSON object which you can use PHP’s json_decode function to manipulate. In action: $opts = array(‘http’ => array( ‘method’ => ‘POST’, ‘header’ => “Content-type: application/x-www-form-urlencoded\r\nX-Requested-With: XMLHttpRequest\r\n”, ‘content’ => http_build_query(array()) ) ); $context = stream_context_create($opts); $result = file_get_contents(“http://webservice.org/route/list/key/mykey/format/json”, false, $context); $jsondata = json_decode($result, true); Nifty.
JSON has become just as big as XML in terms of being the format used to transfer data between AJAX driven web services, meaning that as a PHP developer you will no doubt be doing a lot of dealing with JSON objects. The default way of grabbing JSON data returned by a web service is to call the built in json_decode function which generates what is known as a stdClass. These can be traversed much as you would a normal array using loops: $jsondatastdclass = json_decode($jsoninput); print_r($jsondataarray); foreach ($jsondatastdclass as $object) { foreach ($object as $property=>$value) { echo $property.” has the value “. $value; } } It’s not great, but it does work. However, later version of PHP do allow you to add a second parameter when calling the json_decode function, namely a boolean which then forces the function to return a normal associative array. In practice: $jsondataarray = json_decode($jsoninput, true); print_r($jsondataarray); echo $jsondataarray['data'][0]; And now you know.

JSON, or JavaScript Object Notation, is a lightweight text-based open standard designed for human-readable data interchange. It is derived from the JavaScript scripting language for representing simple data structures and associative arrays, called objects. Despite its relationship to JavaScript, it is language-independent, with parsers available for many languages. In other words, JSON is a good choice for data to be shuttled back and forth between web services via AJAX thanks to its clean and compact nature. However, debugging a big chunk of JSON is not always the easiest task, particularly when it appears to be fault. Enter Chris Dary and his fantastic JSON validator and reformatter, JSONLint! Simply copy or paste your JSON text into the big text box and hit the validate button, and JSONLint will make it look nice and spit out any validation errors it encounters while attempting to parse it. You can also feed it an URL, which it will then take and grab any JSON it detects from its source. Additionally, if you are looking to squeeze your JSON to as small a form as possible, you can use JSONLint as a JSON compressor if you add ?reformat=compress to the URL. Excellent free online tool, and well worth checking out if you do a lot of work with JSON. Related Link: http://jsonlint.com/
Thanks to Twitter, the idea of accessible, useful, and more importantly, simple web services has really latched on in the world of web development. Bascially all a web service is, is a simple URL that when hit with or without specified parameters, returns some data in either JSON or XML (or quite frankly whatever you want it to return) format. Here is a quick example to show you just how easy it is to develop a simple, basic web service of your own in PHP: //database connection $link = mysql_connect(‘localhost’,'username’,'password’) or die(‘Cannot connect to the DB’); mysql_select_db(‘db_name’,$link) or die(‘Cannot select the DB’); //format parameters. Note default of JSON for format parameter $format = key_exists(‘format’, $_POST) ? strtolower($_POST['format']) : ‘json’; $format = in_array($format, array(‘json’, ‘xml’)) ? $format : ‘json’; $code = key_exists(‘code’, $_POST) ? strtolower($_POST['code']) : ‘survey’; $input = trim($code); //output variables $status = 0; $name = ”; $message = ”; //check if we can find a record in the database $campaignrs = mysql_query(“SELECT `campaign-name` FROM `campaigns` WHERE `campaign-code` = ‘$input’ LIMIT 1″); if (mysql_num_rows($campaignrs) > 0) { $campaign = mysql_fetch_assoc($campaignrs); $status = 1; $message = ‘Valid Code’; $name = $campaign['campaign-name']; } else { $status = 0; $message = ‘Invalid Code’; $name = ”; } //build output array $output = array(‘status’ => $status, ‘message’ => $message, ‘name’ => $name); /* output in necessary format */ if ($format == ‘json’) { header(‘Content-type: application/json’); echo json_encode($output); } else { header(‘Content-type: text/xml’); echo ”; echo ” . $status . ”; echo ” . $message [...]

The jQuery UI library is really useful in that it packages a number of jQuery-driven interactions, widgets, effects and utilities into a single package, ready for smooth integration and even easier deployment. One of the many available widgets in the jQuery UI library is Autocomplete, which makes adding autocomplete functionality to an ordinary text searchbox a doddle! Let’s have a look how to implement this when using PHP to provide us with a separate JSON datasource then, shall we? First, if your web page contains a normal textbox within a form that is used to conduct searches, you need to attach the jQuery UI autocomplete functionality with the following code snippet: $(‘#datafilter-search-textbox’).autocomplete({ source: “ajax-search-autocomplete.php”, minLength: 2}); Note the minLength setting of 2. It is often useful to set the number of characters needed to initiate the search so as to minimize the possible amount of search return values for efficiency’s sake. As you can see, we have prompted the autocomplete widget to make use of a file called ajax-search-autocomplete.php as a datasource. This file should look something like this: //… all your database setup stuff $searchresults = array(); $searchterm = (key_exists(‘term’, $_GET)) ? $_GET['term'] : ”; if (strlen($searchterm) > 0) { $results = mysql_query(“SELECT `name` FROM `myTable` WHERE `name` LIKE ‘%$searchterm%’ ORDER BY `name` ASC”); while ($result = mysql_fetch_assoc($results)) { $searchresults[] = $result['filter-name']; } } $searchresults = array_map(“html_entity_decode_custom”, $searchresults); $searchresults = array_map(“get_correct_utf8_mysql_string”, $searchresults); echo json_encode($searchresults); And that is it. Load it up and try it out, and hey presto, you [...]

If you are using the brilliant jQuery DataTables plugin to present your data in nifty dynamic tables, and are using it in a server-side loading context, you have no doubt encountered the issue when a table with a lot of columns (more than 20) fails to load (in other words stays in “processing” mode) when browsing using Internet Explorer (IE).

However, if we tried the same thing with the “message-data” key, you will note that this will fall over syntactically straight away – all because of that silly hyphen (dash).

So what is adding in all these unwanted slashes then? Well the answer of course is PHP’s magic_quotes_gpc ini setting. For those of you who don’t know, essentially this setting came in existence to help programmers who routinely forgot to delimit their strings when inputting them into databases etc.
Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under whichever martial arts dojo is closest at the time, and for the most part, simply enjoys life with his amazing wife and daughter.
Oh, and he draws ever now and then too.
This is a collection of things that he has managed to find the time to scribble down since 2007.
Looking for Something?
Jump to Category: