PHP-JSON Special Characters
Posted: January 28th, 2011 | Author: nramakrishnan | Filed under: Uncategorized | Tags: json, json_decode, json_encode, php, utf8_encode | Comments OffWanted to share this with the group since it took me 3 hours to figure this out.
I was trying to retrieve JSON data from a third party service using a PHP.
In PHP , if you use curl_exec() functions to retrieve JSON data, it returns it in a string form. You can do json_decode($string, true) to retrieve it in an associative array form.
$url = "www.example.com/data.json";
$curl = curl_init();
curl_setopt( $curl, CURLOPT_URL, $url );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
$result = curl_exec( $curl );
curl_close( $curl );
$return = json_decode( $result, true);
echo $return["description"];
All is fine if your json data doesn’t have special characters like “é”, for example
{
"description":"Eric Benét performs.",
"origAirDate":"2011-01-27",
"stationId":11269,
"endTime":
"Thu Jan 27 11:00:00 EST 2011","startTime":"Thu Jan 27 10:00:00 EST 2011",
"title":"The Wendy Williams Show",
"isVisible":true,
"rating":"TV-PG"
}
To handle these special characters make sure that you do
$result = utf8_encode($result); // before json_decode $return = json_decode( $result, true); echo $return["description"];
Hope this helps