Saturday 17 November 2012

handling json with php


I experienced difficulties when I was trying to fetch json formatted data from
 a third party website API, I finally found a solution and I thought I should share
 it with everyone

what you need:

  • PHP Apache server 
  • correct json formatted data
  • Jquery getJson request 

========================================================================
Step 1: 

index.html

<html>
<head>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
     <script type="text/javascript" src="script.js"></script>
</head>
<body onload="getJson()">
<h3>PHP API Example</h3>
<div id="output">

        </div>
</body>
</html>


========================================================================
Step 2: 

in script.js

// getJson Jquery request

function getJson()
{
$.getJSON('json.php', function(data) {
handleJson(data);
});
}

function handleJson(results){
    var listing = results.List;
    var listing_array = [];
    listing_array = listing;
var output = "";
    for (var i = 0; i < 10; i++)
    {  
       var listingId =  listing_array[i].ListingId;
  output += listingId;
  output += "</br>";

}
  var txt=document.getElementById("output")
  txt.innerHTML= output;

}


========================================================================
Step 3: 


 in json.php

<?php
$request =  'http://api.trademe.co.nz/v1/Search/Property/Residential.json?district=4';

$connection = curl_init($request);
curl_setopt($connection, CURLOPT_HEADER, false);
curl_setopt($connection, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($connection);

// Check if for errors
if(curl_errno($connection))
{
// output the error and its number
    echo 'Curl error: ' . curl_error($connection) .' ' .curl_errno($connection) ;
}
curl_close($connection);

echo $response;

?>


HELLO WORLD