Descriere:Acest tutorial arata cum se preia in PHP datele dintr-un sir cu obiect JSON, folosind json_decode().
Download:
Autor:
Sursa (Link-ul oficial): Propria parere:Nu l-am incercat.
Tutorialul:
Obiectul (sirul JSON) poate fi preluat dintr-o sursa externa. De exemplu, de la o adresa URL (cu file_get_contents(), sau cURL) care returneaza un sir cu date in obiect JSON, sau dintr-un fisier text de pe server, sau dintr-o baza de date.
Sa lucram cu un exemplu simplu; un obiect JSON salvat intr-un fisier text pe server.
Fisierul, denumit "sitedata.txt" contine acest sir, un obiect JSON simplu, cu 3 proprietati (url, category, nr_pages):
Cod: Selectaţi tot
{"url": "http://coursesweb.net/", "category": "Web Development", "nr_pages": 400}Cod: Selectaţi tot
<?php
$file = 'sitedata.txt'; // adresa /numele fisierului
// verifica daca fisierul exista
if(file_exists($file)) {
$filedata = file_get_contents($file);
/* Sau, se poate adauga direct acest sir:
$filedata = '{"url": "http://coursesweb.net/", "category": "Web Development", "nr_pages": 400}';
*/
// transforma sirul in obiect al clasei stdClass
$objson = json_decode($filedata, true);
// parcurge obiectul si afiseaza fiecare proprietate si valoarea ei
foreach($objson AS $prop => $val) {
echo '<br/>'. $prop .' - '. $val;
}
}
else echo $file .' nu exista';- Functia json_decode() transforma sirul JSON intr-un Obiect al clasei stdClass. Ca sa obtineti valoarea asociata unei anumite proprietati, se foloseste aceasta sintaxa:
Cod: Selectaţi tot
$valoare = $obiect->nume_proprietate;Cod: Selectaţi tot
$property = 'nume_proprietate';
$valoare = $obiect->{$property};Cod: Selectaţi tot
<?php
// sir cu obiect JSON
$strjson = '{"url": "http://coursesweb.net/", "category": "Web Development", "nr_pages": 400}';
// transforma sirul in obiect al clasei stdClass
$objson = json_decode($strjson);
// preia valoarea unei anumite proprietati
$url = $objson->url;
echo '<br/>'. $url;
// preia valoarea unei proprietati cu numele salvat in variabila
$prop = 'category';
$val = $objson->{$prop};
echo '<br/>'. $val;Daca vreti sa transformati sirul cu obiect JSON intr-un Array asociativ in PHP, adaugati True ca al doilea argument in json_decode().
Sintaxa:
Cod: Selectaţi tot
$arr = json_decode($sir_json, true);Cod: Selectaţi tot
<?php
// sir cu obiect JSON
$strjson = '{"url": "http://marplo.net/", "category": "Diverse", "nr_pages": 1500}';
// transforma sirul in array asociativ
$arrjson = json_decode($strjson, true);
// Test
var_dump($arrjson);
// preia valoarea unui anumit element
$url = $arrjson['url'];
echo '<br/>'. $url;
// preia valoarea unui element cu numele retinut in variabila
$elm = 'category';
$val = $arrjson[$elm];
echo '<br/>'. $val;Iata un exemplu:
Cod: Selectaţi tot
<?php
// sir cu obiect JSON, continand inca un obiect, si un Array
$strjson = '{
"url": "http://marplo.net/",
"category": {"ct1": "Web Development", "ct2": "Web Programming"},
"courses": ["PHP-MySQL", "JavaScript", "HTML", "CSS"]
}';
// converteste sirul intr-un array asociativ
$arrjson = json_decode($strjson, true);
// Afiseaza structura array-ului
echo '<pre>';
var_export($arrjson);
echo '</pre>';
// preia prima categorie "ct1", si al doilea element in "courses"
$ct1 = $arrjson['category']['ct1'];
$course2 = $arrjson['courses'][1];
echo $ct1 .'<br/>'. $course2;Daca sirul cu date de la acel Appi nu este un format JSON corect, trebuie sa prelucrati sirul ca sa obtineti formatul JSON valid inainte de a utiliza json_decode().
De exemplu, datele "info" de la Youtube Api sunt intr-un sir cu obiect JSON, dar sirul in intregime nu este format JSON valid:
Cod: Selectaţi tot
info = { "title" : "DaOne - povestea noastra (feat. Ewa)", "image" : "http://i.ytimg.com/vi/6UjfTKHQ4vo/default.jpg", "length" : "4", "status" : "serving", "progress_speed" : "", "progress" : "", "ads" : "", "pf" : "http://acef.u.aclst.com/ping.php?video_id=6UjfTKHQ4vo&h=2717", "h" : "a148abf7ef86bab307d50d0d9d6177f0" };Cod: Selectaţi tot
<?php
// sir cu date de la Youtube App
$yinfo = 'info = {
"title" : "DaOne - povestea noastra (feat. Ewa)",
"image" : "http://i.ytimg.com/vi/6UjfTKHQ4vo/default.jpg",
"length" : "4",
"status" : "serving",
"progress_speed" : "",
"progress" : "",
"ads" : "",
"pf" : "http://acef.u.aclst.com/ping.php?video_id=6UjfTKHQ4vo&h=2717",
"h" : "a148abf7ef86bab307d50d0d9d6177f0"
};';
/*
Se poate prelua acest sir de la pagina Youtube Api folosind acest cod:
$url = 'http://www.youtube-mp3.org/api/itemInfo/?video_id=6UjfTKHQ4vo&adloc=&r={{datetime}}';
$yinfo = file_get_contents($url);
*/
// preia doar subsirul cu formatul JSON valid
if(preg_match('/{(.*?)}/i', $yinfo, $infojson)) {
// converteste obiectul JSON in array asociativ
$arrjson = json_decode($infojson[0], true);
// afisaza datele de la 'title' si 'image'
$title = $arrjson['title'];
$imgsrc = $arrjson['image'];
echo $title .'<br/>'. $imgsrc;
}
