PHP to convert string to array - php

This may be asked several times but my case is a bit different.
Let me start from the beginning.
$ck_data = db_select('ckeditor_settings', 'cs')
->fields('cs', array('settings'))
->condition('name', 'Advanced', '=')
->execute()
->fetchAssoc();
var_dump($ck_data);
Will give me...
array(1) {
["settings"]=>
string(2144) "a:33:{s:2:"ss";s:1:"2";s:7:"toolbar";s:606:"[
['Source'],
['Cut','Copy','Paste','PasteText','PasteFromWord','-','SpellChecker','Scayt'],
['Undo','Redo','Find','Replace','-','SelectAll'],
['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar'],
['Maximize','ShowBlocks'],
'/',
['Format'],
['Bold','Italic','Underline','Strike','-','Subscript','Superscript','-','RemoveFormat'],
['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','BidiLtr','BidiRtl'],
['Link','Unlink','Anchor','Linkit','LinkToNode','LinkToMenu']
]";s:6:"expand";s:1:"t";s:7:"default";s:1:"t";s:11:"show_toggle";s:1:"t";s:7:"uicolor";s:7:"default";s:12:"uicolor_user";s:7:"default";s:5:"width";s:4:"100%";s:4:"lang";s:2:"en";s:9:"auto_lang";s:1:"t";s:18:"language_direction";s:7:"default";s:15:"allowed_content";s:1:"t";s:19:"extraAllowedContent";s:0:"";s:10:"enter_mode";s:1:"p";s:16:"shift_enter_mode";s:2:"br";s:11:"font_format";s:35:"p;div;pre;address;h1;h2;h3;h4;h5;h6";s:17:"custom_formatting";s:1:"f";s:10:"formatting";a:1:{s:25:"custom_formatting_options";a:6:{s:6:"indent";s:6:"indent";s:15:"breakBeforeOpen";s:15:"breakBeforeOpen";s:14:"breakAfterOpen";s:14:"breakAfterOpen";s:15:"breakAfterClose";s:15:"breakAfterClose";s:16:"breakBeforeClose";i:0;s:10:"pre_indent";i:0;}}s:8:"css_mode";s:4:"none";s:8:"css_path";s:0:"";s:9:"css_style";s:5:"theme";s:11:"styles_path";s:0:"";s:11:"filebrowser";s:4:"none";s:17:"filebrowser_image";s:0:"";s:17:"filebrowser_flash";s:0:"";s:13:"UserFilesPath";s:5:"%b%f/";s:21:"UserFilesAbsolutePath";s:7:"%d%b%f/";s:21:"forcePasteAsPlainText";s:1:"t";s:13:"html_entities";s:1:"f";s:17:"scayt_autoStartup";s:1:"t";s:15:"theme_config_js";s:1:"f";s:7:"js_conf";s:0:"";s:11:"loadPlugins";a:1:{s:12:"drupalbreaks";a:5:{s:4:"name";s:12:"drupalbreaks";s:4:"desc";s:51:"Plugin for inserting Drupal teaser and page breaks.";s:4:"path";s:25:"%plugin_dir%drupalbreaks/";s:7:"buttons";a:1:{s:11:"DrupalBreak";a:2:{s:5:"label";s:11:"DrupalBreak";s:4:"icon";s:22:"images/drupalbreak.png";}}s:7:"default";s:1:"t";}}}"
}
Now what I want is to get the value of toolbar.
$ck_settings = unserialize($ck_data['settings']);
$ck_plugins = $ck_settings['toolbar'];
var_dump($ck_plugins);
Will return...
string(606) "[
['Source'],
['Cut','Copy','Paste','PasteText','PasteFromWord','-','SpellChecker','Scayt'],
['Undo','Redo','Find','Replace','-','SelectAll'],
['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar'],
['Maximize','ShowBlocks'],
'/',
['Format'],
['Bold','Italic','Underline','Strike','-','Subscript','Superscript','-','RemoveFormat'],
['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','BidiLtr','BidiRtl'],
['Link','Unlink','Anchor','Linkit','LinkToNode','LinkToMenu']
]"
My question now is how can I convert $ck_plugins from string to array?

Strange way to be storing that, but it is a string that looks like a PHP array definition:
eval("\$ck_plugins = $ck_plugins;");
print_r($ck_plugins);
If you have control over the data storage, you should probably either store the individual entries in a table or store the entire thing serialized or better in JSON.

Related

How to use preg_split to get the desire result

I have a string like this
1 BDP-105159857 2602 BARUN SINHA MTE02 MTE07 MTE08 PHE11 PHE14
I want to split it like
1, BDP, 105159857, 2602, BARUN SINHA, MTE02, MTE07, MTE08, PHE11, PHE14
If I use
preg_split('/[-, ]+/',$string);
Then it splits the name (BARUN SINHA) in two parts as expected. But I want to keep it together. How to overcome it?
This is a screenshot of my data

Read POST data in AJAX call

I have some Session values that I am constantly changing via Ajax calls. I can't seem to get a handle on the POST data to process it and set the values.
What I am passing to it here is an array of strings like is shown in my code below.
Here is where AJAX calls:
var sessionValues = [];
str = {"PID": "1", "Level": "Main", "MenuName": "Kitchen", "State": "CHECKED"}
sessionValues.push(str);
var postObj = {"sessionData": sessionValues};
$.ajax({
type: 'POST',
data: {'data': postObj},
url: 'setSession.asp'
}).done(function(response){
console.log(response);
})
I have this working fine in a PHP version of the program but my ASP version is not grabbing the data. Here is my PHP ver and the ASP ver as best as I could convert it.
<-- php setSession.php works fine -->
$data = $_POST['data'];
foreach ($data['sessionData'] as $key => $value) {
$projectProduct = "1";
$level = $value["Level"];
$menuName = $value["MenuName"];
$state = $value["State"];
$_SESSION['PID:'.$projectProduct][$level][$menuName]['menu_state'] = $state;
echo "[PID:".$projectProduct."][".$level."][".$menuName."][".$state."]<br>";
}
0 =>>>>> Array<br>[PID:1][Main][Kitchen][CHECKED]
Here I want to do the same thing in ASP
' setSession.asp
data = Request.Form("data")
For Each part In data("sessionData")
projectProduct = part("PID")
level = part("Level")
menuName = part("MenuName")
state = part("State")
Session("PID:" & projectProduct).Item(level).Item(menuName).Remove("menu_state")
Session("PID:" & projectProduct).Item(level).Item(menuName).Add "menu_state", state
response.write("[PID:" & projectProduct&"]["&level&"]["&menuName&"]["&state&"]<br>")
Next
outputs blank
It looks like it never has any data but doesn't throw any errors. Am I reading the POST object correctly?
[edit]
Here is the RAW POST data captured from Fiddler:
data%5BsessionData%5D%5B0%5D%5BPID%5D=1&data%5BsessionData%5D%5B0%5D%5BLevel%5D=Main&data%5BsessionData%5D%5B0%5D%5BMenuName%5D=Kitchen&data%5BsessionData%5D%5B0%5D%5BState%5D=CHECKED
here I used a URL Decode on that string-
data[sessionData][0][PID]=1&data[sessionData][0][Level]=Main Level Plan&data[sessionData][0][MenuName]=Kitchen&data[sessionData][0][State]=CHECKED
This looks like I should be able to loop through the strings now by using
For Each part In Request.Form("data[sessionData]")
but nothing happens. I added a simple loop to look at the request.form and here is what it is seeing:
for each x in Request.Form
Response.Write(x)
Next
' outputs -> data[sessionData][0][PID]data[sessionData][0][Level]data[sessionData][0][MenuName]data[sessionData][0][State]
I guess what this comes down to is just reading through and processing that string correctly, or multiple if more than one is sent. Correct?
The RAW output definitely helps work out what is going on.
What is happening is jQuery is translating the JSON structure into HTTP POST parameters but during the process, it creates some overly complex key names.
If you break down the key value pairs you have something like
data[sessionData][0][PID]=1
data[sessionData][0][Level]=Main Level Plan
data[sessionData][0][MenuName]=Kitchen
data[sessionData][0][State]=CHECKED
As far as Classic ASP is concerned the this is just a collection of string key and value pairs and nothing more.
The correct approach to work out what these keys are is to do what you have done in the question, but with some minor alternations.
For Each x In Request.Form
Response.Write(x) & "=" & Request.Form(x) & "<br />"
Next
Which when outputted as HTML will look similar to the break down shown above.
Armed with the knowledge of what the keys are you should be able to reference them directly from the Request.Form() collection.
Dim pid: pid = Request.Form("data[sessionData][0][PID]")
Response.Write pid
Output:
1

Unable to get stat gathering to work

Using PHP to gather stats from multiple files. Goal is to take the entire first row of data, which is the column name, then take the entire row of data from the row where the first column matches the name specified in the code. These two rows should then be linked to each other, so they can be displayed in a dynamic image.
However, to avoid excessive requests from the external data source, the data is only downloaded once a day by saving it into a json file. The previous day's data is also kept, to perform a difference calculation.
What I'm stuck on is...well, it's not working as intended. The dynamic image does not display and says it cannot be displayed because it contains errors, and the files aren't being created properly. Without any files existing, only the 'old' data file is being created, and the gathered data is saved there in a format that I didn't expect.
Here's the entire PHP code:
<?php
header("Content-Type:image/png");
$root=realpath($_SERVER['DOCUMENT_ROOT']);
function saveTeamData(){
$urls=array('http://www.dc-vault.com/stats/bio.txt','http://www.dc-vault.com/stats/math.txt','http://www.dc-vault.com/stats/misc.txt','http://www.dc-vault.com/stats/overall.txt','http://www.dc-vault.com/stats/phys.txt');
$fullJson=array();
function stats($url){
$json=array();
$team=array("teamName");
$file=fopen($url,'r');
$firstRow=fgetcsv($file,0,"\t");
while($data=fgetcsv($file,0,"\t")){
if(in_array($data[0],$team)){
foreach($firstRow as $indx=>$colName){
if((strpos($colName,'Position')!=0)||(strpos($colName,'Score')!=0)||(strpos($colName,'Team')!=0)){
if(strrpos($colName,'Position')!==false){
$colName=substr($colName,0,strpos($colName,' Position'));
$colName=$colName."Pos";
}else{
$colName=substr($colName,0,strpos($colName,' Score'));
$colName=$colName."Score";
}
$colName=str_replace(' ',',',$colName);
$teamData[$colName]=$data[$indx];
}
}
$json=$teamData;
}
}
fclose($file);
return $json;
}
foreach($urls as $item){
$fullJson=array_merge($fullJson,stats($item));
}
$final_json['teamName']=$fullJson;
$final_json['date']=date("Y-m-d G:i:s",strtotime("11:00"));
$final_json=json_encode($final_json);
file_put_contents("$root/scripts/vaultData.js",$final_json);
return $final_json;
}
if(!file_exists("$root/scripts/vaultData.js")){
$teamData=saveTeamData();
}else{
$teamData=json_decode(file_get_contents("$root/scripts/vaultData.js"));
}
$lastDate=$teamData->date;
$now=date("Y-m-d G:i:s");
$hours=(strtotime($now)-strtotime($lastDate))/3600;
if($hours>=24||!file_exists("$root/scripts/vaultDataOld.js")){
file_put_contents("$root/scripts/vaultDataOld.js",json_encode($teamData));
$teamData=saveTeamData();
}
$team=$teamData->{"teamName"};
$teamOld=json_decode(file_get_contents("$root/scripts/vaultDataOld.js"))->{"teamName"};
$template=imagecreatefrompng("$root/images/vaultInfo.png");
$black=imagecolorallocate($template,0,0,0);
$font='images/fonts/UbuntuMono-R.ttf';
$projects=array();
$subsections=array();
foreach($team as $key=>$val){
$projectName=preg_match("/^(.*)(?:Pos|Score)$/",$key,$cap);
$projectName=str_replace(","," ",$cap[1]);
if(preg_match("/Pos/",$key)){
$$key=(strlen($val)>10?substr($val,0,10):$val);
$delta=$key."Delta";
$$delta=($val - $teamOld->{$key});
$$delta=(strlen($$delta)>5?substr($$delta,0,5):$$delta);
if($projectName!=="Overall"){
if(!in_array($projectName,array("Physical Science","Bio/Med Science","Mathematics","Miscellaneous"))){
$projects[$projectName]["position"]=$$key;
$projects[$projectName]["position delta"]=$$delta*1;
}else{
$subsections[$projectName]["position"]=$$key;
$subsections[$projectName]["position delta"]=$$delta*1;
}
}
}elseif(preg_match("/Score/",$key)){
$$key=(strlen($val)>10?substr($val,0,10):$val);
$delta=$key."Delta";
$$delta=($val - $teamOld->{$key});
$$delta=(strlen($$delta)>9?substr($$delta,0,9):$$delta);
if($projectName!=="Overall"){
if(!in_array($projectName,array("Physical Science","Bio/Med Science","Mathematics","Miscellaneous"))){
$projects[$projectName]["score"]=$$key;
$projects[$projectName]["score delta"]=$$delta;
}else{
$subsections[$projectName]["score"]=$$key;
$subsections[$projectName]["score delta"]=$$delta;
}
}
}
}
$sort=array();
foreach($projects as $key=>$row){
$sort[$key]=$row["score"];
}
array_multisort($sort,SORT_DESC,$projects);
$lastupdated=round($hours,2).' hours ago';
$y=35;
foreach($projects as $name=>$project){
imagettftext($template,10,0,5,$y,$black,$font,$name);
imagettftext($template,10,0,149,$y,$black,$font,$project['position']);
imagettftext($template,10,0,216,$y,$black,$font,$project['position delta']*-1);
imagettftext($template,10,0,257,$y,$black,$font,$project['score']);
imagettftext($template,10,0,331,$y,$black,$font,$project['score delta']);
$y+=20;
}
$y=655;
foreach($subsections as $name=>$subsection){
imagettftext($template,10,0,5,$y,$black,$font,$name);
imagettftext($template,10,0,149,$y,$black,$font,$subsection['position']);
imagettftext($template,10,0,216,$y,$black,$font,$subsection['position delta']*-1);
imagettftext($template,10,0,257,$y,$black,$font,$subsection['score']);
imagettftext($template,10,0,331,$y,$black,$font,$subsection['score delta']);
$y+=20;
}
imagettftext($template,10,0,149,735,$black,$font,$team->{'OverallPos'});
imagettftext($template,10,0,216,735,$black,$font,$OverallPosDelta*-1);
imagettftext($template,10,0,257,735,$black,$font,$OverallScore);
imagettftext($template,10,0,331,735,$black,$font,$OverallScoreDelta);
imagettftext($template,10,0,149,755,$black,$font,$lastupdated);
imagepng($template);
?>
And here is what the data looks like when it is saved:
"{\"teamName\":{\"Folding#HomePos\":\"51\",\"Folding#HomeScore\":\"9994.405407\"},\"date\":\"2014-03-14 11:00:00\"}"
I've omitted most of the data because it just makes things excessively long, and it helps to see the format. Now the reason why its an unexpected output is because I didn't expect trailing slashes to be in it. The older version of this code would output like this:
{"teamName":{"Asteroids#HomePos":"192","Asteroids#HomeScore":"7647.783251"},"date":"2014-03-14 11:00:00"}
So the expected behaviour is to to gather the data from the aforementioned rows in each tab delimited text file, copy the old data into the 'old' data file (vaultDataold), save the new data into the 'current' data file (vaultData), and then display the data from the 'current' file in a dynamic image, along with performing a 'new' minus 'old' calculation on the two files to show the change since the previous day.
Most of this code should work, as I've had it working before in a different way. The issue likely lies somewhere with gathering the row data and saving it, most probably the latter. I'm guessing the slashes are causing the issue.
Turns out that the cause was twofold. Firstly, in my function, I was JSON encoding something that had already been encoded, so when the second file was saved, it appeared as shown in my question. To fix that, I did this:
$final_json['date']=date("Y-m-d G:i:s",strtotime("11:00"));
$encode_json=json_encode($final_json);
file_put_contents("$root/scripts/vaultData.js",$encode_json);
return $final_json;
In addition, as pointed out by another in the comments, I had to add $root to my function, and again within it.

Getting currency conversion data from Yahooapis now that iGoogle is gone

Up until yesterday I had a perfectly working budget organizer site/app working with iGoogle.
Through PHP, using the following little line
file_get_contents('http://www.google.com/ig/calculator?hl=en&q=1usd=?eur');
and similar I was able to get all I needed.
As of today, this is no longer working. When I looked into the issue, what has happened is that Google has retired iGoogle. Bummer!
Anyway, I was looking around elsewhere but I can't find anything that fits my needs. I would REALLY love to just fix it and get it running again by just switching this one line of code (i.e. changing the Google address with the address of some other currency API available) but it seems like none does.
The API from rate-exchange.appspot.com seems like it could be a iGoogle analog but, alas, it never works. I keep getting an "Over Quota" message.
(Here comes an initial question: anybody out there know of a simple, reliable, iGoogle-sort API?)
So I guess the natural thing would be to the Yahoo YQL feature (at least I suppose it is as reliable).
Yahoo's queries look like this:
http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("USDEUR", "USDJPY", "USDBGN")&env=store://datatables.org/alltableswithkeys
What I really can't figure out is how to parse this data. It outputs an XML.
What I used to have is this:
function exchange($inputAmount,$inputCurrency,$outputCurrency) {
$exchange = file_get_contents('http://www.google.com/ig/calculator?hl=en&q='.$inputAmount.$inputCurrency.'=?'.$outputCurrency);
$exchange = explode('"', $exchange);
$exchange = explode('.', $exchange['3']);
$exchange[0] = str_replace(" ", "",preg_replace('/\D/', '', $exchange[0]));
if(isset($exchange[1])){
$exchange[1] = str_replace(" ", "",preg_replace('/\D/', '', $exchange[1]));
$exchange = $exchange[0].".".$exchange[1];
} else{
$exchange = $exchange[0];
}
return $exchange;
}
So the user was able to get the exchange rate from an input currency such as "USD" and an output currency such as "EUR" on a specific amount of money. As I said, this was working swimmingly up until yesterday night.
Any ideas?
Never mind! Solved it!
For anyone interested, here's what I did to get my code to work (with the least chnges possible) with the Yahoo YQL:
// ** GET EXCHANGE INFO FROM YAHOO YQL ** //
$url = 'http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("USDEUR", "EURUSD")&env=store://datatables.org/alltableswithkeys'; //<-- Get the YQL info from Yahoo (here I'm only interested in converting from USD to EUR and vice-versa; you should add all conversion pairs you need).
$xml = simplexml_load_file($url) or die("Exchange feed not loading!"); //<-- Load the XML file into PHP variable.
$exchange = array(); //<-- Build an array to hold the data we need.
for($i=0; $i<2; $i++): //<-- For loop to get data specific to each exchange pair (you should change 2 to the actual amount of pairs you're querying for).
$name = (string)$xml->results->rate[$i]->Name; //<-- Get the name of the pair and turn it into a string (this looks like this: "USD to EUR").
$rate = (string)$xml->results->rate[$i]->Rate; //<-- Do the same for the actual rate resulting from the conversion.
$exchange[$name] = $rate; //<-- Put the data pairs into the array.
endfor; //<-- End for loop. :)
// ** WORK WITH EXCHANGE INFO ** //
$toeur = array( //<-- Create new array specific for conversion to one of the units needed.
'usd' => $exchange['USD to EUR'], //<-- Create an array key for each unit used. In this case, in order to get the conversion of USD to EUR I ask for it from my $exchange array with the pair Name.
'eur' => 1); //<-- The way I coded the app, I found it more practical to also create a conversion for the unit into itself and simply use a 1, which translates into "do not convert"
$tousd = array(
'eur' => $exchange['EUR to USD'],
'usd' => 1);
This is basically all you need to get all the exchange info you want. After that, you use it all something like this:
amount*$toxxx['coin'];
So, say I wanted to know how many Euro is 100 USD right now:
100*$toeur['usd'];
Piece of cake!
Still a very useful solution by QuestionerNo27. Since early 2015, however, Yahoo YQL apparently slightly changed the XML output of their api. 'Name' now no longer translates into a string like 'USD to EUR', but to 'USD/EUR' and should in the code above be referenced this way:
$toeur = array(
'usd' => $exchange['USD/EUR']
instead of
$toeur = array(
'usd' => $exchange['USD to EUR']
and in a similar fashion for other currency conversions.
I created a routine to convert the currency based on #QuestionerNo27 http://jamhubsoftware.com/geoip/currencyconvertor.php?fromcur=USD&tocur=EUR&amount=1 you can consume this
<?php
$fromcur = $_GET['fromcur'];
$tocur = $_GET['tocur'];
$amt = $_GET['amount'];
// ** GET EXCHANGE INFO FROM YAHOO YQL ** //
$url = 'http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("'.$fromcur.$tocur.'")&env=store://datatables.org/alltableswithkeys'; //<-- Get the YQL info from Yahoo (here I'm only interested in converting from USD to EUR and vice-versa; you should add all conversion pairs you need).
$xml = simplexml_load_file($url) or die("Exchange feed not loading!"); //<-- Load the XML file into PHP variable.
$exchange = array(); //<-- Build an array to hold the data we need.
for($i=0; $i<2; $i++): //<-- For loop to get data specific to each exchange pair (you should change 2 to the actual amount of pairs you're querying for).
$name = (string)$xml->results->rate[$i]->Name; //<-- Get the name of the pair and turn it into a string (this looks like this: "USD to EUR").
$rate = (string)$xml->results->rate[$i]->Rate; //<-- Do the same for the actual rate resulting from the conversion.
$exchange[$name] = $rate; //<-- Put the data pairs into the array.
endfor; //<-- End for loop. :)
// ** WORK WITH EXCHANGE INFO ** //
$conv = $fromcur . '/' . $tocur;
$toeur = array( //<-- Create new array specific for conversion to one of the units needed.
$tocur => $amt*$exchange[$conv], //<-- Create an array key for each unit used. In this case, in order to get the conversion of USD to EUR I ask for it from my $exchange array with the pair Name.
$fromcur => $amt,
"ex_amt" =>$amt*$exchange[$conv]); //<-- The way I coded the app, I found it more practical to also create a conversion for the unit into itself and simply use a 1, which translates into "do not convert"
echo json_encode($toeur);
?>

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