SOLVED - html_entity_decode was the solution
My JSON is not decoding. Can anyone spot my mistake?
The JSON string looks like this:
{"ustaAddr":"1198 Industrial Way","ustaCity":"Carmel, CA","ustaPCode":"90210"}
Here is the code:
$newShipTo = stripslashes($aTrans['new_ship_to']);
if ($newShipTo != ""){
$arrShipToAddr = json_decode($newShipTo, TRUE);
$buyer_addr = $arrShipToAddr['ustaAddr'];
$buyer_city = $arrShipToAddr['ustaCity'];
$buyer_pcode= $arrShipToAddr['ustaPCode'];
$shipTo_addr = 'TEST' . '<p>' .$buyer_addr. '</p><p>'.$buyer_city. '</p><p>'.$buyer_pcode. '</p>' ;
}
echo $shipTo_addr;
Result:
TEST
I also tried this:
$shipTo_addr = $arrShipToAddr['ustaAddr'] .' - '. $newShipTo;
Result:
- {"ustaAddr":"1198 Industrial Way","ustaCity":"Carmel, CA","ustaPCode":"90210"}
I also tried this:
$shipTo_addr = $arrShipToAddr->ustaAddr .' - '. $newShipTo;
Result:
- {"ustaAddr":"1198 Industrial Way","ustaCity":"Carmel, CA","ustaPCode":"90210"}
Can anyone spot what I've done wrong? I can't see it...
UPDATE:
The json_decode() statement is failing, but I can't see why.
$shipTo_addr = (is_array($arrShipToAddr)) ? 'yes' : 'no';
Returns "no"
Update Two:
I hard-coded the text string (copy/pasted from the screen result from above test output!), and it worked! (Of course, that's not a solution as the JSON string is dynamically created elsewhere and retrieved from MySQL).
$newShipTo = '{"ustaAddr":"1198 Industrial Way One","ustaCity":"Carmel, CA Two","ustaPCode":"90210 Free"}';
if ($newShipTo != ""){
$arrShipToAddr = json_decode($newShipTo, TRUE);
$shipTo_addr = (is_array($arrShipToAddr)) ? 'yes' : 'no';
}
Result:
yes
I also tried these promising suggestions, but no joy:
$newShipTo = json_encode(stripslashes($aTrans['new_ship_to'])); //re-encode using PHP json_encode
and
$arrShipToAddr = json_decode(utf8_encode($newShipTo), TRUE); //force utf8
It works for me, but you can try :
$arrShipToAddr = json_decode(utf8_encode($newShipTo), TRUE);
Try this:
$newShipTo = '{"ustaAddr":"1198 Industrial Way","ustaCity":"Carmel, CA","ustaPCode":"90210"}';
which then can be decoded it into an array.
Well guys, someone over here asked if there was anything unusual about the field type in the database.
The data, as stored in the field, was html_entitied (looked like this):
{\"ustaAddr\":\"1198 Industrial Way Here\",\"ustaCity\":\"Carmel, CA We\",\"ustaPCode\":\"90210 Go\"}
However, after using stripslashes and json_decode, the string outputted like this:
{"ustaAddr":"176 Industrial Drive","ustaCity":"Carmel, CA","ustaPCode":"90210"}
At first, I thought it was the TEXT field type and thought that changing to a VARCHAR was the solution. Nope.
Using stripslashes and json_decode wasn't enough. To solve the problem, I had to do this:
$newShipTo = stripslashes(html_entity_decode($aTrans['new_ship_to']));
So, the complete code block:
$newShipTo = stripslashes(html_entity_decode($aTrans['new_ship_to']));
if ($newShipTo != ""){
$arrShipToAddr = json_decode($newShipTo, TRUE);
$buyer_addr = $arrShipToAddr['ustaAddr'];
$buyer_city = $arrShipToAddr['ustaCity'];
$buyer_pcode= $arrShipToAddr['ustaPCode'];
$shipTo_addr = '<p>' .$buyer_addr. '</p><p>'.$buyer_city. '</p><p>'.$buyer_pcode. '</p>' ;
}
Related
Hi i have a php file that contain json value. I want to change the value of json variable .But i am not sure how t do that .
my-file.php
<?
$json_data;
$json_varible = json_decode('{"pen_color":"red","book_size":"large","book_color":"red", etc etc }', true);
....
?>
Now I want to change the value of pen_color to green . Please note there are many parameters in json_decode
So i write following
//read the entire string
$str=file_get_contents('my-file.php');
$old_value= "red";
$new_value = "green";
//replace something in the file string - this is a VERY simple example
$str=str_replace($old_value, $new_value,$str);
file_put_contents('my-file.php', $str);
I am sure that this code is wrong. Please help me to solve the issue. I want t change pen_color to green
May be it is that you want
$json_variable = json_decode('{"pen_color":"red","book_size":"large","book_color":"red"}', true);
$json_variable['pen_color'] = 'green';
$json_value = json_encode($json_variable);
file_put_contents('my-file.php', $json_value );
I have this simple code on my site:
$info = file_get_contents('http://freegeoip.net/json/'.$_SERVER['REMOTE_ADDR']);
which displays like this:
{"ip":"123.123.12.1","country_code":"GB","country_name":"United Kingdom","region_code":"ENG","region_name":"England","city":"London","zip_code":"LN1","time_zone":"Europe/London","latitude":30.302,"longitude":-1.123,"metro_code":0}
I am trying to turn this in to an array so that I can import this data to the database using something similar to:
$ip_address = $info['ip'];
$city = $info['city'];
And so on... I have attempted to use $info[1], $info[2] and it just displays { " each character of text. Is there a simple way to do this?
That is a JSON format and you can use the json_decode() function to convert it to either object or array.
So you have:
$info = file_get_contents('http://freegeoip.net/json/'.$_SERVER['REMOTE_ADDR']);
$info = json_decode($info, true);
Then you can use, as you said, the $info['ip'] and $info['city']
Use json_decode
$info_obj = json_decode($info);
Now $info_obj has the info you want, and you can access it this way:
$ip_address = $info_obj->ip;
$city = $info_obj->city;
I have this code for scraping team names from a table
$url = 'http://fantasy.premierleague.com/my-leagues/303/standings/';
$html = #file_get_html($url);
//Cut out the table
$FullTable = $html->find('table[class=ismStandingsTable]',0);
//get the text from the 3rd cell in the row
$teamname = $FullTable->find('td',2)->innertext;
echo $teamname;
This much works.. and gives this output....
Why Always Me?
But when I add these lines..
$teamdetails = $teamname->find('a')->href;
echo $teamdetails;
I get completely blank output.
Any idea why? I am trying to get the /entry/110291/event-history/33/ as one variable, and the Why Always Me? as another.
Instead do this:
$tdhtml = DOMDocument::loadHTML($teamdetails);
$link = $tdhtml->getElementsByTagName('a');
$url = $link->item(0)->attributes->getNamedItem('href')->nodeValue;
$teamdetails = $teamname->find('a')->href;
^^^^^^^^^---- never defined in your code
I also fail to see how your "works" code could possibly work. You don't define $teamname in there either, so all you'd never get is the output of a null/undefined variable, which is...no output all.
Marc B is right, I get that you don't have to initialize a variable, but he is saying you are trying to access a property of said variable:
$teamdetails = $teamname->find('a')->href;
^^^^^^^^^---- never defined in your code
This is essentially:
$teamname = null;
$teamname->find('a')->href;
The problem in your example is that $teamname is a string and you're treating it like a simple_html_dom_node
I am trying to decode some JSON into a php array. Here's the code excerpt:
$getfile="{"fname":"bob","lname":"thomas","cascade":"bthomas","loc":"res","place":"home 2"}";
$arr = json_decode($getfile, true);
$arr['day3'] = $selecter;
echo(print_r($arr));
The only thing that gets returned is '1'. I've checked JSONLint and it is valid json, so I'm wondering why json_decode is failing. I also tried checking what the array is before adding the day3 key to it, and I still return a '1'. Any help is appreciated!
Actual code:
$getfile = "";
$getfile = file_get_contents($file);
if ($getfile == "") {
writeLog("Error reading file.");
}
writeLog("getfile is " . $getfile);
writeLog("Decoding JSON data");
$arr = json_decode($getfile, true);
writeLog("Decoded raw: " . print_r($arr));
writeLog("Editing raw data. Adding data for day " . $day);
$arr['day3'] = $selecter;
writeLog(print_r($arr));
$newfile = json_enconde($arr);
writeLog($newfile);
if (file_put_contents($file, $newfile)) {
writeLog("Wrote file to " . $file);
echo $newfile;
} else {
writeLog("Error writting file");
}
These are the contents of $file (it's a text file)
{"fname":"Bob","lname":"Thomas","cascade":"bthomas","loc":"res","place":"home 2"}
We still don't know what's in your file. However if:
"{"fname":"bob","lname":"thomas","cascade":"bthomas","loc":"res","place":"home 2"}"
Then the extraneous outer double quotes will screw the JSON, and json_decode will return NULL. Use json_last_error() to find out. Might also be a UTF-8 BOM or something else ...
Anyway, the 1 is the result from print_r. print_r outputs directly, you don't need the echo. Also for debugging rather use var_dump()
More specifically you would want the print_r output returned (instead of the boolean success result 1) and then write that to the log.
So use:
writeLog(print_r($arr, TRUE));
Notice the TRUE parameter.
First, use a single quote. That will cause a parse error
$getfile= '{"fname":"bob","lname":"thomas","cascade":"bthomas","loc":"res","place":"home 2"}';
I assume you have already declared $selecter and it has been assigned to some value.
Remove echo from echo(print_r($arr)) You don't need echo. print_r will also output. If you use echo, it will display 1 at the end of array.
The working code:
$getfile = '{"fname":"bob","lname":"thomas","cascade":"bthomas","loc":"res","place":"home 2"}';
$arr = json_decode($getfile, true);
$selecter = 'foobar';
$arr['day3'] = $selecter;
print_r($arr);
Hope this helps.
I had this problem when doing it like this:
if ($arr = json_decode($getfile, true)) {
$arr['day3'] = $selecter;
echo(print_r($arr));
}
Decoding it outside of if was the solution.
I'm trying to get some info out of a decoded JSon string into an array.
I've this code:
$json_d='{ // This is just an example, I normally get this from a request...
"iklive.com":{"status":"regthroughothers","classkey":"domcno"}
}';
$json_a=json_decode($json_d,true);
$full_domain = $domain.$tlds; // $domain = 'iklive' ; $tlds = '.com'
echo $json_a[$full_domain][status];
The problem is, I need to get the value for "status" of "iklive.com" but when I do echo $json_a[$full_domain][status]; it does not work, but if I do it manually like echo $json_a['iklive.com'][status]; (with the quotes there) it works.
I've tried to add the quotes to the variable but without success, how can I do this?
Thanks Everyone!
Thanks to Pekka and jeromegamez I noticed a error in the HTML part of this "problem", the $tlds variable was "com" instead of ".com" -- Sorry by wasting your time with this. I do feel bad now.
Anyway, thanks to jeromegamez and Marc B I discovered that unless status was a constant I need to quote it ;) You can check jeromegamez answer to a detailed explanation of the problem and proper debug.
Sorry.
This works for me:
<?php
$json_d='{ "iklive.com":{"status":"regthroughothers","classkey":"domcno"} }';
$json_a = json_decode($json_d, true);
if (!is_array($json_a)) {
echo "\$json_d is not a valid JSON array\n";
}
$domain = "iklive";
$tld = ".com";
$full_domain = $domain . $tld;
if (!isset($json_a[$full_domain])) {
echo "{$full_domain} is not set in \$json_a\n";
} else {
echo $json_a[$full_domain]['status']."\n";
}
What I did:
Changed json_a[$full_domain][status] to json_a[$full_domain]['status'] - the missing quotes around status don't break your script, but raise a Notice: Use of undefined constant status - assumed 'status'
Added a check if the decoded JSON is actually an array
Added a check whether the key $full_domain is set in $json_a