Abbiamo visto nei due articoli precedenti (JSON 1–2) come usare in modo semplice JSON, e dopo aver gettato le basi ecco un esempio concreto: come fare un motore di ricerca con le API JSON di Yahoo!
Iniziamo subito:
Inseriamo il modulo di ricerca:
<form action='?'>
<input name='keyword' value='<?=$_GET['keyword']?>'/>
<input type='submit' value='Cerca' />
</form><br/>
E come al solito includiamo la nostra libreria JSON (leggi articoli precedenti):
// Includiamo JSON/PEAR
include "JSON.php";
$json = new Services_JSON();
Impostiamo la nostra chiamata al server Yahoo! in modo molto semplice:
// Imposta chiamata a Yahoo!
$keyword = (!empty($_GET['keyword'])) ? $_GET['keyword'] : 'web service architecture';
$num_of_results = 3;
$appid = "YahooDemo"; // Qui inserirai il tuo id Yahoo!
$keyword: Quando nessuno imposterà una parola chiave verrà impostata "web service architecture" come ricerca di dafault.
$num_of_results: Il numero di risultati che visualizzeremo
$appid: è l’id necessario per utilizzare le API Yahoo! Per le tue prove usa pure YahooDemo ma in seguito potrai ottenere una tua appid gratuita su https://login.yahoo.com/config/login_verify2?.src=devnet
Per eseguire la richiesta al server Yahoo! il modo più veloce è il seguente:
// Ottieni il risultato in una stringa $response
$request = "http://api.search.yahoo.com/ImageSearchService/V1/imageSearch?appid={$appid}&query=".urlencode($keyword)."&results={$num_of_results}&output=json";
$response = implode("", file($request));
con file($request) riceviamo la risposta del server in un array che trasformiamo in stringa con la funzione implode().
I dati che ora abbiamo all’interno della stringa $response hanno la sintassi e il formato JSON e per poterli utilizzare ci basta usare la funzione decode()
$obj_result = $json->decode($response);
Ora $obj_result contiene i nostri dati in un formato più facile da usare per PHP, per chi più se ne intende mostro il var_dump($obj_result), gli altri possono andare oltre:
Per darvi un’idea del nostro risultato ecco l’output di var_dump($obj_result) per esempio per la ricerca ‘web service architecture‘:
stdClass Object ( [ResultSet] => stdClass Object ( [totalResultsAvailable] => 9229 [totalResultsReturned] => 3 [firstResultPosition] => 1 [Result] => Array ( [0] => stdClass Object ( [Title] => web_service_out_architecture.jpg [Summary] => looks as depicted in figure 1. In principle, any device that can communicate with a web service interface can be used to invoke mappings and process flows generated by Warehouse Builder. Figure 1: Warehouse Builder code exposed as a web service. This note describes a business case on how to invoke a mapping as a web service. The business case describes a solution that [Url] => http://www.oracle.com/technology/products/warehouse/sdk/Graphics/web_services/web_service_out_architecture.jpg [ClickUrl] => http://www.oracle.com/technology/products/warehouse/sdk/Graphics/web_services/web_service_out_architecture.jpg [RefererUrl] => http://www.oracle.com/technology/products/warehouse/sdk/web_services/owb_code_as_web_service.html [FileSize] => 29900 [FileFormat] => jpeg [Height] => 432 [Width] => 684 [Thumbnail] => stdClass Object ( [Url] => http://re3.yt-thm-a01.yimg.com/image/25/m3/2536194687 [Height] => 94 [Width] => 150 ) ) [1] => stdClass Object ( [Title] => web_service_scenarios.gif [Summary] => Once you've created different scenarios to emulate your various Web service test cases, you can easily switch between them from a combo-box located on the Web service toolbar as shown here: Comprehensive support for all Web service clients and Web service servers, as well as the ability to create and save Web service Scenario Properties further makes Stylus Studio® the [Url] => http://www.stylusstudio.com/images/screenshots/web_service_scenarios.gif [ClickUrl] => http://www.stylusstudio.com/images/screenshots/web_service_scenarios.gif [RefererUrl] => http://www.stylusstudio.com/open_ws_framework.html [FileSize] => 10137 [FileFormat] => gif [Height] => 239 [Width] => 427 [Thumbnail] => stdClass Object ( [Url] => http://re3.yt-thm-a01.yimg.com/image/25/m8/4181434641 [Height] => 78 [Width] => 140 ) ) [2] => stdClass Object ( [Title] => WebServicesArchitecture.jpg [Summary] => , the service registry provides a centralized location for storing service descriptions. A UDDI registry is an example of this type of service registry. Figure 1: Web services architecture Although it is important, the centralized service registry is not the only model for Web service discovery. The simplest form of service discovery is to request a copy of the service [Url] => http://www-128.ibm.com/developerworks/webservices/library/ws-wsilover/WebServicesArchitecture.jpg [ClickUrl] => http://www-128.ibm.com/developerworks/webservices/library/ws-wsilover/WebServicesArchitecture.jpg [RefererUrl] => http://www-106.ibm.com/developerworks/webservices/library/ws-wsilover [FileSize] => 19660 [FileFormat] => jpeg [Height] => 340 [Width] => 430 [Thumbnail] => stdClass Object ( [Url] => http://re3.yt-thm-a02.yimg.com/image/25/m5/3102598382 [Height] => 110 [Width] => 140 ) ) ) ) )
Posso quindi estrapolare tutti i dati che mi servono da $obj_result:
// Prendo i dati che mi servono
$num_results conterrà il numero di risutati trovati
$num_results = $obj_result->ResultSet->totalResultsAvailable;
$results = $obj_result->ResultSet->Result;
$results conterrà l’array con i risultati di ricerca
(Confronta questo codice con il var_dump() precedente)
Infine stampo i risultati:
// Dati sulla lista dei risultati
foreach ($results as $result) {
echo "<b>{$result->Title}</b><br/>";
echo "<a href='{$result->ClickUrl}' target='_blank'><img src='{$result->Thumbnail->Url}' border=0 /></a><br /><br />";
}
Ora che abbiamo finito…
Clicca qui per vedere l’ESEMPIO COMPLETO del motore di ricerca JSON
Oppure scarica il codice completo dell’esempio.
Aspettiamo vostri consigli, critiche e giudizi per questa serie di articoli!