Display PostgreSQL JSON in PHP - php

I am querying 3 tables in PostgreSQL and converting the result into a nested json object. I am using PHP (and the Slim framework) as my application code. I am able to return a valid nested JSON object using PostgreSQL's built-in json operators. However, I'm having trouble rendering that JSON object in PHP.
PHP's json_encode operator seems to be trying to perform a JSON conversion on the provided obect (which is already in JSON format). And I can't get PHP to simply echo, print (or print_r) out the valid result provided by PostgreSQL. PHP keeps adding extra characters to the result.... I've tried :
(a) not using the PostgreSQL JSON operators,
(b) using PHP's json_decode before using json_encode,
(c) simply running echo and print_r statements, and
(d) I just started toying with using str_replace to remove the extraneous characters, but that is starting to feel scuzzy...
I'm pretty sure I'm doing something obviously wrong. I'm just at a standstill on this one. Any help is greatly appreciated!
The 3 tables are :
1. Company
2. Contact
3. Pic
CONTACT >----(:company_id)----- COMPANY ----(:company_id)-----< PIC
(A single company can have many contacts, and can have many pics... No relationship b/w the CONTACT and PIC tables)
HERE IS THE PHP CODE WHICH USES THE POSTGRESQL QUERY :
<?php
$app->get('/companies/{id}', function($request)
{
$db = pg_connect("host=localhost dbname=cool_db_name user=postgres")
or die('Could not connect: ' . pg_last_error());
$id = $request->getAttribute('id');
$query = "
SELECT row_to_json(t)
FROM (
SELECT company_id, company_name, company_street, company_city, company_state, company_zip, active_ind
, (
SELECT array_to_json(array_agg(row_to_json(c)))
FROM (
SELECT ct.contact_id, ct.contact_lname, ct.contact_fname, ct.contact_email, ct.active_ind
FROM contact ct
WHERE ct.company_id = c.company_id
ORDER by ct.contact_lname
) c
) AS contacts
, (
SELECT array_to_json(array_agg(row_to_json(p)))
FROM (
SELECT p.pic_id, p.pic_location, p.active_ind
FROM pic p
WHERE p.company_id = c.company_id
AND p.active_ind = 1
ORDER by p.pic_id
) p
) AS pics
FROM company c
WHERE c.alive_ind = 1 AND c.company_id = " . $id . "
) t
;";
$result = pg_query($db, $query);
while($row = pg_fetch_assoc($result))
{
$data[] = $row;
}
if(isset($data))
{
header('Content-Type: application/json');
echo json_encode($data);
}
});
1. Again, if I run that PostgreSQL query by itself, the result is VALID JSON (below) :
{
"company_id": 1,
"company_name": "Company #1",
"company_street": "111 Fun Ave",
"company_city": "Creve Coeur",
"company_state": "MO",
"company_zip": "10002",
"active_ind": 1,
"contacts": [{
"contact_id": 1,
"contact_lname": "Figgis",
"contact_fname": "Cyril",
"contact_email": "figgis#gmail.com",
"active_ind": 1
}, {
"contact_id": 2,
"contact_lname": "Kane",
"contact_fname": "Lana",
"contact_email": "lana#gmail.com",
"active_ind": 1
}, {
"contact_id": 3,
"contact_lname": "Tunt",
"contact_fname": "Cheryl",
"contact_email": "crazy#gmail.com",
"active_ind": 1
}],
"pics": [{
"pic_id": 1,
"pic_location": "profile/pic_900.jpg",
"active_ind": 1
}, {
"pic_id": 2,
"pic_location": "profile/pic_901.jpg",
"active_ind": 1
}, {
"pic_id": 3,
"pic_location": "profile/pic_902.jpg",
"active_ind": 1
}, {
"pic_id": 4,
"pic_location": "profile/pic_903.jpg",
"active_ind": 1
}]
}
(sorry for the poor formatting... it looks better in jsonlint.com)
2. ...but when I run that same query in the PHP application I get the following result (WEIRD JSON) :
[{"row_to_json":"{\"company_id\":1,\"company_name\":\"Company #1\",\"company_street\":\"111 Fun Ave\",\"company_city\":\"Creve Coeur\",\"company_state\":\"MO\",\"company_zip\":\"10002\",\"active_ind\":1,\"contacts\":[{\"contact_id\":1,\"contact_lname\":\"Figgis\",\"contact_fname\":\"Cyril\",\"contact_email\":\"figgis#gmail.com\",\"active_ind\":1},{\"contact_id\":2,\"contact_lname\":\"Kane\",\"contact_fname\":\"Lana\",\"contact_email\":\"lana#gmail.com\",\"active_ind\":1},{\"contact_id\":3,\"contact_lname\":\"Tunt\",\"contact_fname\":\"Cheryl\",\"contact_email\":\"crazy#gmail.com\",\"active_ind\":1}],\"pics\":[{\"pic_id\":1,\"pic_location\":\"profile/pic_900.jpg\",\"active_ind\":1},{\"pic_id\":2,\"pic_location\":\"profile/pic_901.jpg\",\"active_ind\":1},{\"pic_id\":3,\"pic_location\":\"profile/pic_902.jpg\",\"active_ind\":1},{\"pic_id\":4,\"pic_location\":\"profile/pic_903.jpg\",\"active_ind\":1}]}"}]
Like I said, I'm at a loss right now. Any help would be GREATLY appreciated. Thanks!

So, using that last escaped data format, you could do:
$noSlahes = str_replace("\", "", $yourEscapedJsonString);
This removes the slashes, replacing them with nothing. Now:
$jsonObject = json_decode($noSlahes);
Then, select rowToJson for it to be identical to your properly formatted JSON:
echo $jsonObject->row_to_json;

If someone else hits this problem and finds this question, both of the suggested answers are not an answer but a dirty workaround. The real problem lays on the query at the beginning and not on the php side.
Don't use ARRAY_AGG(ROW_TO_JSON())
Don't wrap any JSON function of PostgreSQL in ARRAY_AGG(), which will convert the JSON into a PostgreSQL Array and effectively will brake the JSON format escaping the quotes. A PosgreSQL array is not a JSON or a PHP array.
Use instead JSON_AGG()
The right aggregation function of JSON objects returned by any PostgreSQL JSON function like ROW_TO_JSON, JSON_BUILD_OBJECT etc, is done using JSON_AGG() function.

header('Content-Type: application/json');
$noSlashes = str_replace("\\","",$data); /* no need for json_encode() */
$hope = array_values($noSlashes[0]);
foreach($hope as $key => $value)
{
print $value;
}

Related

Changing json format in php

I have a json output from a database quesry that looks as follows:
[
{
"name": 1,
"value": "27.18161362"
},
{
"name": 2,
"value": "323.69645128"
},
{
"name": 3,
"value": "23.16249181"
}
]
I am trying to plug this into a script that will make charts from the data. The script requires the data to be in the following format:
{"script":
[
{"name":"1","value":27.18161362},
{"name":"2","value":323.69645128},
{"name":"3","value":23.16249181}
]
}
If it is not formatted in this way, the script claims that it is not valid json and contains no valud json head.
The output does use a valid json content header but that appears not to be enough for the script I am using.
So the question is, how can I convert the json output from a database call shown in first example, into the format the script is looking for show in the second example.
Code that creates json is fairly standard:
$stmt = $db3->prepare("SELECT week AS name, SUM(he.earnings) AS value FROM hotspot_earnings he INNER JOIN emrit_hotspots eh ON eh.hotspot_name = he.hotspot_name WHERE year = '2020' GROUP BY year, week");
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
header('Content-type: application/json; charset=UTF-8');
echo json_encode($row, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$stmt = $db3->prepare("SELECT week AS name, SUM(he.earnings) AS value FROM hotspot_earnings he INNER JOIN emrit_hotspots eh ON eh.hotspot_name = he.hotspot_name WHERE year = '2020' GROUP BY year, week");
$stmt->execute();
// Change here
$row = ['script' => $stmt->fetchAll(PDO::FETCH_ASSOC)];
Not sure if you can edit the initial json output with php. If it's called by AJAX and you can control the php file you can try something like this. Just build the new array.
$new_array = array('script' => $row);
echo json_encode($new_array, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

order of JSON with multiple arrays in php with varying number of objects

I have never needed json previously, so I have almost zero experience...
I am outputting multiple arrays into a json file using the following code:
$file= 'myfile.json';
$contents = array('name' => $name,'busname' => $busname,'busdesc' => $busdesc, etc, etc);
$newcont=json_encode($contents, JSON_PRETTY_PRINT);
print_r($newcont);
file_put_contents($file, $newcont);
This is working as expected, and the output gives me something similar to this:
"name": [
"joe blogs",
"random name 2",
"random name 3",
etc,
etc
],
"busname": [
"ABC business",
"DEF business",
"HIJ business",
etc,
etc
],
"busdesc": [
"We do stuff",
"We do other stuff",
"We don't do anything",
etc,
etc
],
etc
Is it possible to (with a simple method) have the output to be more like:
"id1": [ "joe blogs", "ABC business", "We do stuff", etc ]
"id2": [ "random name 2", "DEF business", "We do other stuff", etc ]
"id3": [ "random name 3", "HIJ business", "We don't do anything", etc ]
etc
Layout is not particularly important, but getting them grouped together is.
I have had little success with getting relevant results from Google searches.
The reason I ask for a simple method, is that I am sure I can come up with some fancy loop that counts the number of entries first, then loops to keep adding the relevant data - and that may well be the answer, but I just wanted to know.
Many thanks
Edit:
I have undeleted this as my attempt at fixing did not work.
Here is the code:
$results = mysqli_query($con,"SELECT * FROM membersites WHERE id>0 ORDER BY id, busname");
$totalmem = mysqli_num_rows($results);
while($business = mysqli_fetch_array($results))
{
$r1 = $business['id'];
$id[]=$r1;
$r2 = $business['name'];
$name[]=$r2;
$r4 = $business['busname'];
$busname[]=$r4;
$r5 = $business['busdesc'];
$busdesc[]=$r5;
$all[] = "'id:''".$r1."''name:''".$r2."''busname:''".$r4."''busdesc:''".$r5."'";
}
$contents = array('members' => $all);
$newcont=json_encode($contents, JSON_PRETTY_PRINT);
print_r($newcont);
This almost worked as all the data is grouped correctly, however I am only getting one object (members) with all the users inside, not individual objects for each user.
Again, please bare in mind that this is the first project that I have had to output any json files.
Any help will be appreciated :)
Edit 2 (for clarity)
Final output needs to look like this
{
[
{
"id":"1",
"name":"joe blogs",
"busname":"ABC business",
"busdesc":"We do stuff"
},
{
"id":"2",
"name":"joe blogs",
"busname":"random name 2",
"busdesc":"We do other stuff"
},
etc
]
}
This file is going to be read by a mobile app - the app developer has just told me that it need to be in this format.
Apologies for being awkward.
When you loop on your records from DB, build a multi-dimensional array:
while($business = mysqli_fetch_array($results))
{
$all[] = [
'id' => $business['id'],
'name' => $business['name'],
'busname' => $business['busname'],
'busdesc' => $business['busdesc'],
];
// or
$all[] = $business;
// or
$all[ $business['id'] ] = $business;
}
Then you can encode your multidimensional array into JSON like this:
$newcont = json_encode($all, JSON_FORCE_OBJECT | JSON_PRETTY_PRINT);
the addition of JSON_FORCE_OBJECT will preserve numerical keys (i.e. when you add using $all[])
I'd recommend using PDO for database access instead of mysqli, which was originally developed as a stopgap replacement for the old mysql extension. But, using mysqli this should work:
$result = $con->query("SELECT id, name, busname, busdesc FROM membersites WHERE id > 0 ORDER BY id, busname");
$data = $result->fetch_all();
$json = json_encode($data, JSON_PRETTY_PRINT);
file_put_contents($file, $json);
You should avoid using SELECT * when possible. It reduces overhead, and ensures that you know the order of columns you're receiving. The mysqli_result::fetch_all() function pulls all the records at once, so no need for a loop.

Getting values from a PHP Object

I am trying to figure out how to echo the genre value from an object created with this programme wrapper that requests json data from 'The Movie Database'. I'm so stuck and grappling to understand Object-oriented PHP so any help would be great.
I think the fact it is 'nested' (if that's the correct terminology) might be the issue.
<?php
include("tmdb/tmdb-api.php");
$apikey = "myapi_key";
$tmdb = new TMDB($apikey, 'en', true);
$idMovie = 206647;
$movie = $tmdb->getMovie($idMovie);
// returns a Movie Object
echo $movie->getTitle().'<br>';
echo $movie->getVoteAverage().'<br>';
echo '<img src="'. $tmdb->getImageURL('w185') . $movie->getPoster() .'"/></li><br>';
echo $movie->genres->id[28]->name;
?>
All of the other values are echoed just fine but I can't seem to get at genres. The json data looks like this ( some of it).
{
"adult":false,
"backdrop_path":"\/fa9qPNpmLtk7yC5KZj9kIxlDJvG.jpg",
"belongs_to_collection":{
"id":645,
"name":"James Bond Collection",
"poster_path":"\/HORpg5CSkmeQlAolx3bKMrKgfi.jpg",
"backdrop_path":"\/6VcVl48kNKvdXOZfJPdarlUGOsk.jpg" },
"budget": 0,
"genres":[
{ "id": 28, "name": "Action" },
{ "id": 12, "name": "Adventure" },
{ "id": 80, "name": "Crime" }
],
"homepage":"http:\/\/www.sonypictures.com\/movies\/spectre\/",
"id":206647,
"imdb_id":"tt2379713",
"original_language":"en",
"original_title":"SPECTRE",
"overview":"A cryptic message from Bond\u2019s past sends him on a trail to uncover a sinister organization. While M battles political forces to keep the secret service alive, Bond peels back the layers of deceit to reveal the terrible truth behind SPECTRE."
}
$movie->genres->id[28]->name
This assumes that id is an array and you want the item with index number 28 from it. What you want is the item containing an id with the value 28 without knowing its index number.
There's no easy way to get to it. You'd have to loop over the array $movie->genres and output the right one.
Maybe like this:
$n = 28;
// loop over genres-array
foreach($movie->genres as $i=>$g){
// check if id of item has right value and if so print it
if($g->id == $n){
echo $g->name;
// skip rest of loop if you only want one
break;
}
}

HTML is NULL in JSON object from json_encode

I have a ajax call calling a php file who runs a long php function which returns a JSON encoded array/object. Now I need to send HTML also into the ajax response. I thought about sending the HTML inside the array.
Is that a good practise?
Right now I cannot get it working, I get a NULL as value for that property. Don't know why.
$statHTML = '<table>';
foreach ($toHTML as $key=>$value) {
$statHTML.= '
<tr class="'.$key.'">
<td class="side">'.$value[0].'</td>
<td>'.$value[2].' '.$value[1].'</td>
</tr>';
}
$statHTML.= '</table>';
// echo $statHTML; // - this works
//function return
$answer = array('mostSearched'=>$mostSearched,
'timeOfDay' => $timeOfDay,
'mostSearchedDays'=>$mostSearchedDays,
'statHTML' => $statHTML
);
return json_encode($answer);
The ajax response from the console before the JSON.parse():
{
"mostSearched": {
"title": "Most serached houses",
"colNames": [21],
"rowNames": [2013],
"rows": [1]
},
"timeOfDay": {
"title": "Time of search",
"colNames": ["07:30"],
"rowNames": ["07:30"],
"rows": [
[1]
]
},
"mostSearchedDays": {
"title": "Most searched days",
"colNames": ["2013-12-21", "2013-12-22", "2013-12-23", "2013-12-24", "2013-12-25", "2013-12-26", "2013-12-27"],
"rowNames": ["2013-12-21", "2013-12-22", "2013-12-23", "2013-12-24", "2013-12-25", "2013-12-26", "2013-12-27"],
"rows": [
[1, 1, 1, 1, 1, 1, 1]
]
},
"statHTML": null
}
From php.net:
Parameters
value
The value being encoded. Can be any type except a resource.
All string data must be UTF-8 encoded.
So use:
$answer = array('mostSearched'=>$mostSearched,
'timeOfDay' => $timeOfDay,
'mostSearchedDays'=>$mostSearchedDays,
'statHTML' => utf8_encode($statHTML)
);
return json_encode($answer);
Most likely the build-in JSON parser used by PHP cannot properly parse the HTML, the easiest way to solve the issue is to base64 encode the html on the server, and then decode it on the client, using either the newer atob and btoa base64 methods, or one of the many polyfills out there.
use base64_enccode in this at the time of conversion
$answer = array('statHTML'=>base64_encode('<h1>html in here</h1>'));
echo json_encode($answer);exit;
And at the time of getting response from ajax
atob(response.statHTML);
Hope you understand how it works

PHP JSON Google Definitions - accessing a value

EDIT#4: json_decode is failing and returning null on a seemingly valid json string. See below for more info
I am new to JSON/JSONP and I'm running into constant trouble accessing the values in the returned JSON with PHP. I have stripped the JSONP callback without issue using code I found on this board. I am getting a JSONP result from http://www.google.com/dictionary/json?callback=a&sl=en&tl=en&q=love and struggling to access the first result for the meaning. It's a quite complex result, and I need to access the first meaning (in the node "text") from the below JSON result.
http://pastebin.com/hBTeBTUL
My best attempt was:
if (isset($json->primaries[1]->entries[1]->terms[1]->text))
The above was the best I could do, I just keep getting errors trying to return that text node saying it is undefined. I'd prefer to work with objects rather than associative arrays too, if possible, so please avoid telling me to set it to return assoc array.
Any help would be greatly appreciated. I'm really stuck :P
EDIT:
$json->primaries[1]->entries[1]->terms[0]->text didn't seem to work either. Here is the complete script. Ignore the $params array as it is not used, was going to use it to generate the query.
The script has been edited since when I first posted, I had an invalid JSON object, but the error seems to be fixed as it will now parse through JSON formatters.
The error i'm getting trying to print the value out is
PHP Notice: Trying to get property of non-object in /home/outil2/Plugins/GDefine.php on line 23
EDIT#2: added json_decode which was in my original solution, but got lost in the second version
<?php
class GDefine extends Plugin {
public static $enabled = TRUE;
public function onReceivedData($data) {
if ($data["message"][0] == ".def") {
$params = array (
"callback" => "a",
"sl" => "en",
"tl" => "en",
"q" => $data["message"][1]
);
$jsonp = file_get_contents(
"http://www.google.com/dictionary/json?callback=a&sl=en&tl=en&q=" . $data["message"][1]);
$json = json_decode(substr($jsonp, 2, strlen($jsonp)-12));
var_dump($json);
print_r($json->primaries[1]->entries[1]->terms[0]->text);
if (isset($json->primaries[1]->entries[1]->terms[0]->text)) {
$text = $this->bold("Google Definition: ");
$text .= $this->teal($json->primaries[1]->entries[1]->terms[0]->text);
$this->privmsg($data["target"], $text);
} else {
$this->privmsg($data["target"], "error error error");
}
}
}
}
EDIT #3: this is the string I'm trying to json_decode, after using substr to remove the callback function, but am getting a NULL value returned on var_dump($json)
{"query":"love","sourceLanguage":"en","targetLanguage":"en","primaries":[{"type":"headword","terms":[{"type":"text","text":"love","language":"en","labels":[{"text":"Noun","title":"Part-of-speech"}]},{"type":"phonetic","text":"/lÉv/","language":"und"},{"type":"sound","text":"http://www.gstatic.com/dictionary/static/sounds/de/0/love.mp3","language":"und"}],"entries":[{"type":"related","terms":[{"type":"text","text":"loves","language":"und","labels":[{"text":"plural"}]}]},{"type":"meaning","terms":[{"type":"text","text":"An intense feeling of deep affection","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"babies fill parents with intense feelings of \x3cem\x3elove\x3c/em\x3e","language":"en"}]},{"type":"example","terms":[{"type":"text","text":"their \x3cb\x3e\x3cem\x3elove\x3c/em\x3e for\x3c/b\x3e their country","language":"en"}]}]},{"type":"meaning","terms":[{"type":"text","text":"A deep romantic or sexual attachment to someone","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"it was \x3cem\x3elove\x3c/em\x3e at first sight","language":"en"}]},{"type":"example","terms":[{"type":"text","text":"they were both \x3cb\x3ein \x3cem\x3elove\x3c/em\x3e with\x3c/b\x3e her","language":"en"}]},{"type":"example","terms":[{"type":"text","text":"we were slowly \x3cb\x3efalling in \x3cem\x3elove\x3c/em\x3e\x3c/b\x3e","language":"en"}]}]},{"type":"meaning","terms":[{"type":"text","text":"A personified figure of \x3cem\x3elove\x3c/em\x3e, often represented as Cupid","language":"en"}]},{"type":"meaning","terms":[{"type":"text","text":"A great interest and pleasure in something","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"his \x3cb\x3e\x3cem\x3elove\x3c/em\x3e for\x3c/b\x3e football","language":"en"}]},{"type":"example","terms":[{"type":"text","text":"we share a \x3cb\x3e\x3cem\x3elove\x3c/em\x3e of\x3c/b\x3e music","language":"en"}]}]},{"type":"meaning","terms":[{"type":"text","text":"Affectionate greetings conveyed to someone on one\x27s behalf","language":"en"}]},{"type":"meaning","terms":[{"type":"text","text":"A formula for ending an affectionate letter","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"take care, lots of \x3cem\x3elove\x3c/em\x3e, Judy","language":"en"}]}]},{"type":"meaning","terms":[{"type":"text","text":"A person or thing that one \x3cem\x3eloves\x3c/em\x3e","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"she was \x3cb\x3ethe \x3cem\x3elove\x3c/em\x3e of his life\x3c/b\x3e","language":"en"}]},{"type":"example","terms":[{"type":"text","text":"their two great \x3cem\x3eloves\x3c/em\x3e are tobacco and whiskey","language":"en"}]}]},{"type":"meaning","terms":[{"type":"text","text":"A friendly form of address","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"it\x27s all right, \x3cem\x3elove\x3c/em\x3e","language":"en"}]}]},{"type":"meaning","terms":[{"type":"text","text":"Used to express affectionate approval for someone","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"don\x27t fret, there\x27s a \x3cem\x3elove\x3c/em\x3e","language":"en"}]}]},{"type":"meaning","terms":[{"type":"text","text":"(in tennis, squash, and some other sports) A score of zero; nil","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"\x3cem\x3elove\x3c/em\x3e fifteen","language":"en"}]},{"type":"example","terms":[{"type":"text","text":"he was down two sets to \x3cem\x3elove\x3c/em\x3e","language":"en"}]}]}]},{"type":"headword","terms":[{"type":"text","text":"love","language":"en","labels":[{"text":"Verb","title":"Part-of-speech"}]},{"type":"phonetic","text":"/lÉv/","language":"und"},{"type":"sound","text":"http://www.gstatic.com/dictionary/static/sounds/de/0/love.mp3","language":"und"}],"entries":[{"type":"related","terms":[{"type":"text","text":"loved","language":"und","labels":[{"text":"past participle"}]},{"type":"text","text":"loves","language":"und","labels":[{"text":"3rd person singular present"}]},{"type":"text","text":"loving","language":"und","labels":[{"text":"present participle"}]},{"type":"text","text":"loved","language":"und","labels":[{"text":"past tense"}]}]},{"type":"meaning","terms":[{"type":"text","text":"Feel a deep romantic or sexual attachment to (someone)","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"do you \x3cem\x3elove\x3c/em\x3e me?","language":"en"}]}]},{"type":"meaning","terms":[{"type":"text","text":"Like very much; find pleasure in","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"I\x27d \x3cem\x3elove\x3c/em\x3e a cup of tea, thanks","language":"en"}]},{"type":"example","terms":[{"type":"text","text":"I just \x3cem\x3elove\x3c/em\x3e dancing","language":"en"}]},{"type":"example","terms":[{"type":"text","text":"a fun-\x3cem\x3eloving\x3c/em\x3e girl","language":"en"}]}]}]}]}
I json_decode that and it returns NULL :(
You're trying to access an object that doesn't exist. Your code:
if (isset($json->primaries[1]->entries[1]->terms[1]->text)) // Doesn't exist
There's no terms[1] in entries[1] in primaries[1]. There's just 1 item; terms[0]. I think this will work for example:
if (isset($json->primaries[1]->entries[1]->terms[0]->text))
The first item in the array is indexed by 0 not 1, maybe that's your mistake.
Edit:
You also need to decode the JSON, change:
$json = substr($jsonp, 2, strlen($jsonp)-12);
to:
$json = json_decode(substr($jsonp, 2, strlen($jsonp)-12));
Edit:
You need to escape some unescaped characters in the JSON as well. Add this to your code:
Change:
$json = json_decode(substr($jsonp, 2, strlen($jsonp)-12));
to:
$json = substr($jsonp, 2, strlen($jsonp) - 12);
$json = str_replace("\\", "\\\\", $json);
$json = json_decode($json);

Categories