PHP: json_decode on copyright symbol - php
I am using PHP 5.2.9-2 with WAMP on a Windows machine.
I am having a problem trying to decode a JSON string that contains a copyright symbol in one of the elements. The function always return NULL. My first thought was to attempt to escape the character, but the htmlentities() function just returns the same string. I tried to pass the arguments like so:
htmlentities($json, ENT_NOQUOTES, 'utf-8');
But that only returns an empty string. I thought about trying ENT_IGNORE, but it is only available in PHP 5.3.0+. How can I get this JSON string correctly encoded into a JSON object when it has this copyright symbol in it?
I do not have control over the source of the JSON and yes, it is properly formatted. I am getting the information from a 3rd party API and the string has a file size of a little more than 20MB. I use ajax to get the JSON then save it to a file and later read it in to the PHP.
EDIT: Here's a link to the JSON I'm working with.
DROPBOX LINK
The specific line is this
...{"Ranking":1115,"Name":"©lutchGod-","Rank":55,"TotalExp":8571865,"KDR":1.14,"Kill":66459,"HeadShot":11785,"clan":" pG "}...
EDIT2:
To clarify, I am looking to convert this JSON string into a JSON object so that I can use a foreach loop to extract each part and process it. If I end up with a string at the end, I get no where. I have been using the decode function like so to get associative arrays:
json_decode($json, true);
EDIT 3:
I've put together a barebones version of the problem. All I do is read in the JSON from a txt file and attempt to run it through the json_decode() function. With the copyright symbol, it fails. Without it, it works fine. Here it is:
***Contents of SOExampleJSON.txt***
{"Ranking":1115,"Name":"©lutchGod-","Rank":55,"TotalExp":8571865,"KDR":1.14,"Kill":66459,"HeadShot":11785,"clan":" pG "}
***PHP Code***
<?php
echo '<pre>';
$rawJson = file_get_contents('SOExampleJSON.txt');
var_dump($rawJson);
$json = json_decode($rawJson);
var_dump($json);
echo '</pre>';
?>
***Output***
string(120) "{"Ranking":1115,"Name":"©lutchGod-","Rank":55,"TotalExp":8571865,"KDR":1.14,"Kill":66459,"HeadShot":11785,"clan":" pG "}"
NULL
***Output when copyright is removed***
string(119) "{"Ranking":1115,"Name":"lutchGod-","Rank":55,"TotalExp":8571865,"KDR":1.14,"Kill":66459,"HeadShot":11785,"clan":" pG "}"
object(stdClass)#1 (8) {
["Ranking"]=>
int(1115)
["Name"]=>
string(9) "lutchGod-"
["Rank"]=>
int(55)
["TotalExp"]=>
int(8571865)
["KDR"]=>
float(1.14)
["Kill"]=>
int(66459)
["HeadShot"]=>
int(11785)
["clan"]=>
string(4) " pG "
}
I need the object as it is above, but I need to preserve the "Name" in such a way that I can compare it later. I don't care what format it is in, as long as it is usable. As far as I know, this is the only name with such a symbol. The symbol isn't even allowed as part of a name, but the developers have obviously goofed somewhere in their checking and now I'm having to find a way around it until they fix it. I reported it 2 months ago and there still hasn't been anything done about it, so I don't expect it to be any time soon.
yuck, PHP 5.2.X...
i think this hack should work
<?php
$json=base64_decode('eyJSYW5raW5nIjoxMTE1LCJOYW1lIjoiwqlsdXRjaEdvZC0iLCJSYW5rIjo1NSwiVG90YWxFeHAiOjg1NzE4NjUsIktEUiI6MS4xNCwiS2lsbCI6NjY0NTksIkhlYWRTaG90IjoxMTc4NSwiY2xhbiI6IiBwRyAifQ==');
assert(strlen($json)>1);
$parsedJson=json_decode($json,true);
assert($parsedJson!=null);
?>
<script type="text/javascript">
var str=atob("<?php echo base64_encode(var_export($parsedJson,true));?>");
alert(str);
</script>
though, when you upgrade to 5.4.0 or newer, this would be a much better approach
<?php
$json=base64_decode('eyJSYW5raW5nIjoxMTE1LCJOYW1lIjoiwqlsdXRjaEdvZC0iLCJSYW5rIjo1NSwiVG90YWxFeHAiOjg1NzE4NjUsIktEUiI6MS4xNCwiS2lsbCI6NjY0NTksIkhlYWRTaG90IjoxMTc4NSwiY2xhbiI6IiBwRyAifQ==');
assert(strlen($json)>1);
$parsedJson=json_decode($json,true,1337);
assert($parsedJson!=null);
echo '<pre>';
ob_start();
var_dump($parsedJson);
echo htmlentities(ob_get_clean(),ENT_SUBSTITUTE);
echo '</pre>';
Also, your problem is probably not the json decoding, its the html encoding, you need PHP 5.3.0 or higher for ENT_IGNORE, and you need PHP 5.4.0 for ENT_SUBSTITUTE , and without at least ENT_IGNORE: "If the input string contains an invalid code unit sequence within the given encoding an empty string will be returned, unless either the ENT_IGNORE or ENT_SUBSTITUTE flags are set." ( http://php.net/manual/en/function.htmlentities.php ) ..i guess the # counts. but use assert just to be sure about that. also use error_reporting(E_ALL); , preferably even exception_error_handler ( see here http://php.net/manual/en/class.errorexception.php )
This code works for me using PHP 5.6.6 on Windows. To preserve the © I'm using urlencode before json_encode and then I use urldecode after using json_decode to get it back.
<?php
$test = urlencode('{"Ranking":1115,"Name":"©lutchGod-","Rank":55,"TotalExp":8571865,"KDR":1.14,"Kill":66459,"HeadShot":11785,"clan":" pG "}');
$test2= json_encode($test);
var_dump(urldecode(json_decode($test2)));
Edit: update to address latest comment
This time on Ubuntu (PHP 5.5.9-1ubuntu4.6 (cli) (built: Feb 13 2015 19:17:11))
header('Content-Type: text/html; charset=utf-8');
$test = '{"Ranking":1115,"Name":"©lutchGod-","Rank":55,"TotalExp":8571865,"KDR":1.14,"Kill":66459,"HeadShot":11785,"clan":" pG "}';
$test2 = json_decode($test);
print_r($test2);
Output:
stdClass Object
(
[Ranking] => 1115
[Name] => ©lutchGod-
[Rank] => 55
[TotalExp] => 8571865
[KDR] => 1.14
[Kill] => 66459
[HeadShot] => 11785
[clan] => pG
)
Related
PHP parse_str of URL query returns array keys with 'amp' in key name
Environment: Wordpress (latest) on test site on Host (JustHost), with PHP version 5.4.43. Using parse_str on a URL query, the resulting array returns array key names of amp;keyname . Example code: $querystring = "ie=UTF8&qid=1468851514&sr=8-1&keywords=there&tag=sitename-20"; parse_str($querystring, $queryarray); echo "<pre>"; print_r($queryarray); echo "</pre>"; Returns Array ( [ie] => UTF8 [amp;qid] => 1468851514 [amp;sr] => 8-1 [amp;keywords] => there [amp;tag] => sitename-20 ) Why is the 'amp;' in the key name? Is this a PHP version issue (it seems to work OK in a EasyPHP local environment - version 5.4.24, but not on my test WP server on my hosting place)? Or am I confused (again)?
&'amp; must only be used when outputting URLs in HTML/XML data. You can try use html_entity_decode() $querystring = "ie=UTF8&qid=1468851514&sr=8-1&keywords=there&tag=sitename-20"; parse_str(html_entity_decode($querystring), $queryarray); echo "<pre>"; print_r($queryarray); echo "</pre>"; I hope it help.
If you are sure that $querystring doesn't contain other encoded entities, you can use html_entity_decode, as #Hugo E Sachez suggests. But in some complex systems $querystring may come from a place that you don't have control of, and it may contain entities that were encoded on purpose as a safety measure, like ", or <, or > etc... So, if you decode all entities, and then parse data, and then somehow return this data to user, probably some unwanted <script> can be executed. I assume it would be safer to replace only & with &, and keep other entities encoded. Like this: parse_str(str_replace('&', '&', $querystring), $queryarray); Correct me if I am wrong
Character Loss converting _GET Array to URL string
Having a very bizarre issue with the conversion of a $_GET request into a string. (PHP 5.2.17) Here is a small snippet of the problem area of the array from print_r(): _GET (array) ... [address_country_code] => GB [address_name] => Super Mario [notify_version] => 3.7 ... There are two cases the _GET data is used: Case 1): Saved then used later: // Script1.php $data = json_encode($_GET); # > Save to MySQL Database ($data) // Script2.php (For Viewing & Testing URL later) # > Load from Database ($result) echo http_build_query(json_decoded($result,true)); Result of above array snippet: (CORRECT OUTPUT) address_country_code=GB&address_name=Super+Mario¬ify_version=3.7 Case 2): Used in same script as Case 1) just before its saved in Case 1): // Script1.php echo http_build_query($_GET); Results in: (INCORRECT OUTPUT) address_country_code=GB&address_name=Super+Mario¬ify_version=3.7 How is it possible that a few chars are output as a ¬ in case 2 yet case 1 is fine! It is driving me insane :( I have tried also instead of using http_build_query a custom function that generates the url using urlencode() in the Key and Value of the foreach loop, this just resulted in the the ¬ being changed to %C2%AC in one of my test cases!
Everything is ok with your data. You can verify it if you do: $query = http_build_query($_GET); parse_str($query, $data); print_r($data); you will get the correct uncorrupted data. And the reason why you see ¬ symbol is how browser interprets html entities. ¬ is represented as ¬ But browser will render it even without semicolon at the end.
You're most likely displaying this data in a web browser and that is interpreting ¬ as special HTML entity. Pls see this: https://code.google.com/p/doctype-mirror/wiki/NotCharacterEntity Try doing var_dump(http_build_query($_GET)) instead of: echo http_build_query($_GET) and see HTML source to get/verify actual string.
So, even though both cases output to web a web browser and both convert from an array using http_build_query(). I fixed problem in Case 2 by replacing http_build_query (Case 1 still uses it..) with this function: htmlspecialchars(http_build_query($_GET));
Why is json_encode adding backslashes?
I've been using json_encode for a long time, and I've not had any problems so far. Now I'm working with a upload script and I try to return some JSON data after file upload. I have the following code: print_r($result); // <-- This is an associative array echo json_encode($result); // <-- this returns valid JSON This gives me the following results: // print_r result Array ( [logo_url] => http://mysite.com/uploads/gallery/7f/3b/f65ab8165d_logo.jpeg [img_id] => 54 [feedback] => Array ( [message] => File uploaded [success] => 1 ) ) // Echo result {"logo_url":"http:\/\/mysite.com\/uploads\/gallery\/7f\/3b\/f65ab8165d_logo.jpeg","img_id":"54","feedback":{"message":"File uploaded","success":true}} Can anyone tell me why json_encode adds slashes? update #Quentin said that something is happening between json_encode and .parseJSON and he's right. Doing a alert(data.toSource()); gives me the dollowing result: ({response:"{\"logo_url\":\"http:\\/\\/storelocator.com\\/wp-content\\/uploads\\/gallery\\/7f\\/3b\\/71b9520cfc91a90afbdbbfc9d2b2239b_logo.jpeg\",\"img_id\":\"62\",\"feedback\":{\"message\":\"File uploaded\",\"success\":true}}", status:200}) And this is not valid JSON. It also adds the status:200 and I have no idea where this comes from. Could it be that the Plupload bind does something to my returned data? This is my js script: uploader.bind('FileUploaded', function(up, file, data) { alert(data.toSource()); $('#' + file.id + " b").html("100%"); });
Just use the "JSON_UNESCAPED_SLASHES" Option (added after version 5.4). json_encode($array,JSON_UNESCAPED_SLASHES);
I just came across this issue in some of my scripts too, and it seemed to be happening because I was applying json_encode to an array wrapped inside another array which was also json encoded. It's easy to do if you have multiple foreach loops in a script that creates the data. Always apply json_encode at the end. Here is what was happening. If you do: $data[] = json_encode(['test' => 'one', 'test' => '2']); $data[] = json_encode(['test' => 'two', 'test' => 'four']); echo json_encode($data); The result is: ["{\"test\":\"2\"}","{\"test\":\"four\"}"] So, what you actually need to do is: $data[] = ['test' => 'one', 'test' => '2']; $data[] = ['test' => 'two', 'test' => 'four']; echo json_encode($data); And this will return [{"test":"2"},{"test":"four"}]
Can anyone tell me why json_encode adds slashes? Forward slash characters can cause issues (when preceded by a < it triggers the SGML rules for "end of script element") when embedded in an HTML script element. They are escaped as a precaution. Because when I try do use jQuery.parseJSON(response); in my js script, it returns null. So my guess it has something to do with the slashes. It doesn't. In JSON "/" and "\/" are equivalent. The JSON you list in the question is valid (you can test it with jsonlint). Your problem is likely to do with what happens to it between json_encode and parseJSON.
This happens because the JSON format uses ""(Quotes) and anything in between these quotes is useful information (either key or the data). Suppose your data was : He said "This is how it is done". Then the actual data should look like "He said \"This is how it is done\".". This ensures that the \" is treated as "(Quotation mark) and not as JSON formatting. This is called escape character. This usually happens when one tries to encode an already JSON encoded data, which is a common way I have seen this happen. Try this $arr = ['This is a sample','This is also a "sample"']; echo json_encode($arr); OUTPUT: ["This is a sample","This is also a \"sample\""]
Make sure your php script has the right header or it will add the slashes header('Content-Type: application/json');
I had a very similar problem, I had an array ready to be posted. in my post function I had this: json = JSON.stringfy(json); the detail here is that I'm using blade inside laravel to build a three view form, so I can go back and forward, I have in between every back and forward button validations and when I go back in the form without reloading the page my json get filled by backslashes. I console.log(json) in every validation and realized that the json was treated as a string instead of an object. In conclution i shouldn't have assinged json = JSON.stringfy(json) instead i assigned it to another variable. var aux = JSON.stringfy(json); This way i keep json as an object, and not a string.
json_encode will always add slashes. Check some examples on the manual HERE This is because if there are some characters which needs to escaped then they will create problem. To use the json please Parse your json to ensure that the slashes are removed Well whether or not you remove slashesthe json will be parsed without any problem by eval. <?php $array = array('url'=>'http://mysite.com/uploads/gallery/7f/3b/f65ab8165d_logo.jpeg','id'=>54); ?> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script type="text/javascript"> var x = jQuery.parseJSON('<?php echo json_encode($array);?>'); alert(x); </script> This is my code and i m able to parse the JSON. Check your code May be you are missing something while parsing the JSON
json_decode + json_encode combo not creating original JSON
I have some JSON that I got through an API call, and I run json_decode on it, grab an array from it, then re-encode it with json_encode. The result however is not the same JSON; it's messing up with the URLs. How do I make it encode properly? original {"created_at":"Mon, 19 Mar 2012 01:34:41 +0000","entities":{"hashtags":[{"text":"stanford","indices":[23,32]}],"urls":[{"url":"http:\/\/t.co\/Of4z6jKG","expanded_url":"http:\/\/360.io\/5sZc2T","display_url":"360.io\/5sZc2T","indices":[33,53]}],"user_mentions":[]},"from_user":"rayfk","from_user_id":335143881,"from_user_id_str":"335143881","from_user_name":"Raymond Kennedy","geo":{"coordinates":[37.4227,-122.1753],"type":"Point"},"id":181554251733020673,"id_str":"181554251733020673","iso_language_code":"en","metadata":{"result_type":"recent"},"profile_image_url":"http:\/\/a0.twimg.com\/profile_images\/1468102095\/image_normal.jpg","profile_image_url_https":"https:\/\/si0.twimg.com\/profile_images\/1468102095\/image_normal.jpg","source":"<a href="http:\/\/www.occipital.com\/360\/app" rel="nofollow">360 Panorama<\/a>","text":"View from mid lake log #stanford http:\/\/t.co\/Of4z6jKG","to_user":null,"to_user_id":null,"to_user_id_str":null,"to_user_name":null} after decode/encode combo {"created_at":"Mon, 19 Mar 2012 01:34:41 +0000","entities":{"hashtags":[{"text":"stanford","indices":[23,32]}],"urls":[{"url":"http:\/\/t.co\/Of4z6jKG","expanded_url":"http:\/\/360.io\/5sZc2T","display_url":"360.io\/5sZc2T","indices":[33,53]}],"user_mentions":[]},"from_user":"rayfk","from_user_id":335143881,"from_user_id_str":"335143881","from_user_name":"Raymond Kennedy","geo":{"coordinates":[37.4227,-122.1753],"type":"Point"},"id":181554251733020673,"id_str":"181554251733020673","iso_language_code":"en","metadata":{"result_type":"recent"},"profile_image_url":"http:\/\/a0.twimg.com\/profile_images\/1468102095\/image_normal.jpg","profile_image_url_https":"https:\/\/si0.twimg.com\/profile_images\/1468102095\/image_normal.jpg","source":"<a href="http:\/\/www.occipital.com\/360\/app" rel="nofollow">360 Panorama<\/a>","text":"View from mid lake log #stanford http:\/\/t.co\/Of4z6jKG","to_user":null,"to_user_id":null,"to_user_id_str":null,"to_user_name":null} Those are the full snippets, but the culprit is this: original "source":"<a href="http:\/\/www.occipital.com\/360\/app" rel="nofollow">360 Panorama<\/a>" after "source":"<a href="http:\/\/www.occipital.com\/360\/app" rel="nofollow">360 Panorama<\/a>"
I'm not sure what is causing it but you can correct it by applying the html_entity_decode() function to the after version. This will change things such as < or " back to their original form. Depending on how it affects your quoting, there are a few flags you can pass it as well to get the result you need. ENT_COMPAT: Will convert double-quotes and leave single-quotes alone. ENT_QUOTES: Will convert both double and single quotes. ENT_NOQUOTES: Will leave both double and single quotes unconverted. [EDIT] Run your broken JSON through this function: function fixDoubleQuotedJSON($broken_json) { return str_replace('"','\\"',$broken_json); }
http://codepad.org/DMkAS2iR They seem to be equal, except at an unexcepted place: before: "id":181554251733020673,"id_str" after: "id":181554251733020000,"id_str" Those id's won't really match after "lossless" json transforms, and JSON_BIGINT_AS_STRING option is supported from PHP 5.4. Codepad's php version is 5.2.5 by the way;
parsing JSON data with PHP....large dataset
below is the dataset I am trying to parse and put into db... I am using this code $json = json_decode($string); $json[0]['segments']['layover'] gives access error... also sizeof($json) returns nothing... $json doesn't return null,is checked, prints with echo var_dump($json) I have attempted to foreach through this...doesn't work.. tried an array type and is saying that I am illegal access stdIN object...is there anything as easy as DOMDocument() to walk through json? ---json [{"legs":[{"segments":[{"layover":{"hours":1,"minutes":28},"totalTravelingTime":{"hours":1,"minutes":10},"departureAirport":{"airportCode":"ABE","airportCity":"Allentown","airportName":"Allentown (ABE)","airportCityState":"Allentown, PA"},"arrivalAirport":{"airportCode":"IAD","airportCity":"Washington","airportName":"Washington (IAD)","airportCityState":"Washington, DC"},"departureDate":1328811900000,"arrivalDate":1328816100000,"flightNumber":"3866","elapsedNumberOfDays":0,"departureDateTime":{"month":2,"year":2012,"timeZone":"GMT-05:00","day":9,"second":0,"minute":25,"hour":10,"milliSecond":0,"xsdTimeType":"DATETIME_WITH_TIMEZONE","dateTimeString":"2012-02-09T10:25:00-05:00"},"segmentLegSequenceIndex":1,"airCarrierCode":"UA","aircraftType":"Saab 340/340B","aircraftCode":"SF3","airline":{"activeState":"ACTIVE","airlineCode":"UA","airlineName":"UNITED","majorAirline":true,"imageFilename":"UA.gif","preferredAirline":false},"bookingCode":"S","cabinClass":"3","seatMapAvailable":true,"segmentSequenceIndex":1,"formattedDepartureTime":"10:25am","formattedArrivalTime":"11:35am","operatedBy":"/UNITED EXPRESS/COLGAN AIR","formattedDepartureDate":"2/9/12","formattedArrivalDate":"2/9/12","operatingAirlineCode":"","wiFiAvailable":false},{"layover":{"hours":1,"minutes":5},"totalTravelingTime":{"hours":3,"minutes":27},"departureAirport":{"airportCode":"IAD","airportCity":"Washington","airportName":"Washington (IAD)","airportCityState":"Washington, DC"},"arrivalAirport":{"airportCode":"DFW","airportCity":"Dallas","airportName":"Dallas (Dallas-Fort Worth Intl.)","airportCityState":"Dallas, TX"},"departureDate":1328821380000,"arrivalDate":1328830200000,"flightNumber":"3801","elapsedNumberOfDays":0,"departureDateTime":{"month":2,"year":2012,"timeZone":"GMT-05:00","day":9,"second":0,"minute":3,"hour":13,"milliSecond":0,"xsdTimeType":"DATETIME_WITH_TIMEZONE","dateTimeString":"2012-02-09T13:03:00-05:00"},"segmentLegSequenceIndex":1,"airCarrierCode":"UA","aircraftType":"Canadian Regional Jet 700","aircraftCode":"CR7","airline":{"activeState":"ACTIVE","airlineCode":"UA","airlineName":"UNITED","majorAirline":true,"imageFilename":"UA.gif","preferredAirline":false},"bookingCode":"S","cabinClass":"3","seatMapAvailable":true,"segmentSequenceIndex":2,"formattedDepartureTime":"1:03pm","formattedArrivalTime":"3:30pm","operatedBy":"/UNITED EXPRESS/MESA AIRLINES","formattedDepartureDate":"2/9/12","formattedArrivalDate":"2/9/12","operatingAirlineCode":"","wiFiAvailable":false},{"totalTravelingTime":{"hours":0,"minutes":50},"departureAirport":{"airportCode":"DFW","airportCity":"Dallas","airportName":"Dallas (Dallas-Fort Worth Intl.)","airportCityState":"Dallas, TX"},"arrivalAirport":{"airportCode":"ABI","airportCity":"Abilene","airportName":"Abilene (ABI)","airportCityState":"Abilene, TX"},"departureDate":1328834100000,"arrivalDate":1328837100000,"flightNumber":"2975","elapsedNumberOfDays":0,"departureDateTime":{"month":2,"year":2012,"timeZone":"GMT-06:00","day":9,"second":0,"minute":35,"hour":16,"milliSecond":0,"xsdTimeType":"DATETIME_WITH_TIMEZONE","dateTimeString":"2012-02-09T16:35:00-06:00"},"segmentLegSequenceIndex":1,"airCarrierCode":"AA","aircraftType":"Embraer RJ145","aircraftCode":"ER4","airline":{"activeState":"ACTIVE","airlineCode":"AA","airlineName":"American Airlines","majorAirline":true,"imageFilename":"AA.gif","preferredAirline":false},"bookingCode":"L","cabinClass":"3","seatMapAvailable":true,"segmentSequenceIndex":3,"formattedDepartureTime":"4:35pm","formattedArrivalTime":"5:25pm","operatedBy":"/AMERICAN EAGLE","formattedDepartureDate":"2/9/12","formattedArrivalDate":"2/9/12","operatingAirlineCode":"","wiFiAvailable":false}],"carriers":["UA","UA","AA"],"departureDateTime":{"month":2,"year":2012,"timeZone":"GMT-05:00","day":9,"second":0,"minute":25,"hour":10,"milliSecond":0,"xsdTimeType":"DATETIME_WITH_TIMEZONE","dateTimeString":"2012-02-09T10:25:00-05:00"},"arrivalDateTime":{"month":2,"year":2012,"timeZone":"GMT-06:00","day":9,"second":0,"minute":25,"hour":17,"milliSecond":0,"xsdTimeType":"DATETIME_WITH_TIMEZONE","dateTimeString":"2012-02-09T17:25:00-06:00"},"airLineImageFilePath":"","elapsedDays":0,"departureTime":"2012/02/09 10:25:00 PST","arrivalTime":"2012/02/09 17:25:00 PST","departureDate":1328811900000,"arrivalDate":1328837100000,"arrivalAirport":{"airportCode":"ABI","airportCity":"Abilene","airportName":"Abilene (ABI)","airportCityState":"Abilene, TX"},"legSequenceIndex":1,"departureAirport":{"airportCode":"ABE","airportCity":"Allentown","airportName":"Allentown (ABE)","airportCityState":"Allentown, PA"},"departureDateFormat":"2012/02/09","arrivalDateFormat":"Feb. 9","formattedDepartureTime":"10:25am","formattedArrivalTime":"5:25pm","hasTrainLeg":false,"stops":2,"totalTravelingHours":{"hours":8,"minutes":0},"formattedMiles":"1,495","hasBusLeg":false,"formattedDepartureDate":"2/9/12","formattedDepartureDateTime":"2/9/12","departureDateFormat1":"Thu. Feb. 9","formattedArrivalDate":"2/9/12","durationTimeInMins":480,"locationDistanceCount":1495,"locationDistanceUnit":"miles","seatMapAvailableForAnySegment":true,"firstBagFreeAirlines":false,"showOBFeeMessageForLeg":false,"airlineWithBagFeeMsg":false,"airlineWithNoBagFeeMsg":false,"legIndex":1}],"inboundLegsInfo":[{"taxes":43.22,"basePrice":808.01,"taxesAndFees":50.22,"ceilTotalPrice":859.0,"localeFormattedTaxAndFees":"$50","localeFormatBasePrice":"$808","bookingFee":7.0,"t":858.23,"ft":"$858","fab":"$808","fat":"$858","faf":"$50","tripId":30,"s":2,"c":"AA"},{"taxes":43.22,"basePrice":1028.01,"taxesAndFees":50.22,"ceilTotalPrice":1079.0,"localeFormattedTaxAndFees":"$50","localeFormatBasePrice":"$1,028","bookingFee":7.0,"t":1078.23,"ft":"$1,078","fab":"$1,028","fat":"$1,078","faf":"$50","tripId":50,"s":2,"c":"UA"}],"airFareBasisCode":"SA0MN","flightFareType":"PUBLISHED","seatCount":1,"totalPrice":858.23,"fare":{"maxLccPrice":0.0,"minLccPrice":0.0,"totalFlightFare":858.23,"currencyCode":"USD","fees":{"amount":7.00,"currency":"USD","double":7.0,"currencyCode":"USD"},"taxes":{"amount":43.22,"currency":"USD","double":43.22,"currencyCode":"USD"},"baseFare":{"amount":808.01,"currency":"USD","double":808.01,"currencyCode":"USD"},"totalFare":{"amount":858.23,"currency":"USD","double":858.23,"currencyCode":"USD"},"totalBaseFare":808.01,"localeTotalBaseFare":"$808","localeTotalFlightTaxes":"$43","totalFlightTaxes":43.22,"localeTotalFlightFare":"$858","localeTotalFees":"$7","localeTotalFlightTaxesAndFees":"$50","totalFees":7.0,"totalTaxesAndFees":{"amount":50.22,"currency":"USD","double":50.22,"currencyCode":"USD"},"flightFare":{"currencyCode":"USD","basePrice":808.01,"taxes":43.22}},"flightId":"30","showFareDisplayName":false,"fareDisplayName":"Published","firstBagFreeAirline":false,"operatedByFeeDisplayFeatureEnabled":false,"hasFare":true,"localeFormatAvgBasePrice":"$808","localeFormatAvgTotalPrice":"$858","stops":2,"bargainFare":false,"fareName":"published","selectedFlightPara":"30:30:FLTIStr","fareTypeCode":"P","airProviderId":2,"ccfeeAirline":"","displayLCCFareName":false,"noOfTicketsLeft":7,"seatPreview":true,"localeFormatAvgTotalTaxesAndFees":"$50","priceIllegal":false,"fareTypeValue":"1","showOBFeeMessageForModule":false,"completeTrip":false,"hasAirlineWithBagFee":false,"hasAirlineWithNoBagFee":false,"isABestTrip":true,"carrierList":["AA"],"isFirstBagFreePos":true},{"legs":[{"segments":[{"layover":{"hours":1,"minutes":41},"totalTravelingTime":{"hours":2,"minutes":22},"departureAirport":{"airportCode":"ABE","airportCity":"Allentown","airportName":"Allentown (ABE)","airportCityState":"Allentown, PA"},"arrivalAirport":{"airportCode":"ATL","airportCity":"Atlanta","airportName":"Atlanta (Hartsfield-Jackson Atlanta Intl.)","airportCityState":"Atlanta, GA"},"departureDate":1328818020000,"arrivalDate":1328826540000,"flightNumber":"4355","elapsedNumberOfDays":0,"departureDateTime":{"month":2,"year":2012,"timeZone":"GMT-05:00","day":9,"second":0,"minute":7,"hour":12,"milliSecond":0,"xsdTimeType":"DATETIME_WITH_TIMEZONE","dateTimeString":"2012-02-09T12:07:00-05:00"},"segmentLegSequenceIndex":1,"airCarrierCode":"DL","aircraftType":"Canadair RJ","aircraftCode":"CRJ","airline":{"activeState":"ACTIVE","airlineCode":"DL","airlineName":"Delta","majorAirline":true,"imageFilename":"DL.gif","preferredAirline":false},"bookingCode":"Q","cabinClass":"3","seatMapAvailable":true,"segmentSequenceIndex":1,"formattedDepartureTime":"12:07pm","formattedArrivalTime":"2:29pm","operatedBy":"/PINNACLE DBA DELTA CONNECTION","formattedDepartureDate":"2/9/12","formattedArrivalDate":"2/9/12","operatingAirlineCode":"9E","wiFiAvailable":false},{"layover":{"hours":1,"minutes":5},"totalTravelingTime":{"hours":2,"minutes":30},"departureAirport":{"airportCode":"ATL","airportCity":"Atlanta","airportName":"Atlanta (Hartsfield-Jackson Atlanta Intl.)","airportCityState":"Atlanta, GA"},"arrivalAirport":{"airportCode":"DFW","airportCity":"Dallas","airportName":"Dallas (Dallas-Fort Worth Intl.)","airportCityState":"Dallas, TX"},"departureDate":1328832600000,"arrivalDate":1328838000000,"flightNumber":"1810","elapsedNumberOfDays":0,"departureDateTime":{"month":2,"year":2012,"timeZone":"GMT-05:00","day":9,"second":0,"minute":10,"hour":16,"milliSecond":0,"xsdTimeType":"DATETIME_WITH_TIMEZONE","dateTimeString":"2012-02-09T16:10:00-05:00"},"segmentLegSequenceIndex":1,"airCarrierCode":"DL","aircraftType":"Boeing 757-200","aircraftCode":"752","airline":{"activeState":"ACTIVE","airlineCode":"DL","airlineName":"Delta","majorAirline":true,"imageFilename":"DL.gif","preferredAirline":false},"bookingCode":"Q","cabinClass":"3","seatMapAvailable":true,"segmentSequenceIndex":2,"formattedDepartureTime":"4:10pm","formattedArrivalTime":"5:40pm","operatedBy":"","formattedDepartureDate":"2/9/12","formattedArrivalDate":"2/9/12","operatingAirlineCode":"","wiFiAvailable":false},{"totalTravelingTime":{"hours":0,"minutes":50},"departureAirport":{"airportCode":"DFW","airportCity":"Dallas","airportName":"Dallas (Dallas-Fort Worth Intl.)","airportCityState":"Dallas, TX"},"arrivalAirport":{"airportCode":"ABI","airportCity":"Abilene","airportName":"Abilene (ABI)","airportCityState":"Abilene, TX"},"departureDate":1328841900000,"arrivalDate":1328844900000,"flightNumber":"2773","elapsedNumberOfDays":0,"departureDateTime":{"month":2,"year":2012,"timeZone":"GMT-06:00","day":9,"second":0,"minute":45,"hour":18,"milliSecond":0,"xsdTimeType":"DATETIME_WITH_TIMEZONE","dateTimeString":"2012-02-09T18:45:00-06:00"},"segmentLegSequenceIndex":1,"airCarrierCode":"AA","aircraftType":"Embraer EMB-140","aircraftCode":"ERD","airline":{"activeState":"ACTIVE","airlineCode":"AA","airlineName":"American Airlines","majorAirline":true,"imageFilename":"AA.gif","preferredAirline":false},"bookingCode":"L","cabinClass":"3","seatMapAvailable":true,"segmentSequenceIndex":3,"formattedDepartureTime":"6:45pm","formattedArrivalTime":"7:35pm","operatedBy":"/AMERICAN EAGLE","formattedDepartureDate":"2/9/12","formattedArrivalDate":"2/9/12","operatingAirlineCode":"","wiFiAvailable":false}],"carriers":["DL","DL","AA"],"departureDateTime":{"month":2,"year":2012,"timeZone":"GMT-05:00","day":9,"second":0,"minute":7,"hour":12,"milliSecond":0,"xsdTimeType":"DATETIME_WITH_TIMEZONE","dateTimeString":"2012-02-09T12:07:00-05:00"},"arrivalDateTime":{"month":2,"year":2012,"timeZone":"GMT-06:00","day":9,"second":0,"minute":35,"hour":19,"milliSecond":0,"xsdTimeType":"DATETIME_WITH_TIMEZONE","dateTimeString":"2012-02-09T19:35:00-06:00"},"airLineImageFilePath":"","elapsedDays":0,"departureTime":"2012/02/09 12:07:00 PST","arrivalTime":"2012/02/09 19:35:00 PST","departureDate":1328818020000,"arrivalDate":1328844900000,"arrivalAirport":{"airportCode":"ABI","airportCity":"Abilene","airportName":"Abilene (ABI)","airportCityState":"Abilene, TX"},"legSequenceIndex":10,"departureAirport":{"airportCode":"ABE","airportCity":"Allentown","airportName":"Allentown (ABE)","airportCityState":"Allentown, PA"},"departureDateFormat":"2012/02/09","arrivalDateFormat":"Feb. 9","formattedDepartureTime":"12:07pm","formattedArrivalTime":"7:35pm","hasTrainLeg":false,"stops":2,"totalTravelingHours":{"hours":8,"minutes":28},"formattedMiles":"1,581","hasBusLeg":false,"formattedDepartureDate":"2/9/12","formattedDepartureDateTime":"2/9/12","departureDateFormat1":"Thu. Feb. 9","formattedArrivalDate":"2/9/12","durationTimeInMins":508,"locationDistanceCount":1581,"locationDistanceUnit":"miles","seatMapAvailableForAnySegment":true,"firstBagFreeAirlines":false,"showOBFeeMessageForLeg":false,"airlineWithBagFeeMsg":false,"airlineWithNoBagFeeMsg":false,"legIndex":1}],"inboundLegsInfo":[{"taxes":43.22,"basePrice":808.01,"taxesAndFees":50.22,"ceilTotalPrice":859.0,"localeFormattedTaxAndFees":"$50","localeFormatBasePrice":"$808","bookingFee":7.0,"t":858.23,"ft":"$858","fab":"$808","fat":"$858","faf":"$50","tripId":39,"s":2,"c":"DL"},{"taxes":43.22,"basePrice":808.01,"taxesAndFees":50.22,"ceilTotalPrice":859.0,"localeFormattedTaxAndFees":"$50","localeFormatBasePrice":"$808","bookingFee":7.0,"t":858.23,"ft":"$858","fab":"$808","fat":"$858","faf":"$50","tripId":39,"s":2,"c":"AA"}],"airFareBasisCode":"QA00A0NJ","flightFareType":"PUBLISHED","seatCount":1,"totalPrice":858.23,"fare":{"maxLccPrice":0.0,"minLccPrice":0.0,"totalFlightFare":858.23,"currencyCode":"USD","fees":{"amount":7.00,"currency":"USD","double":7.0,"currencyCode":"USD"},"taxes":{"amount":43.22,"currency":"USD","double":43.22,"currencyCode":"USD"},"baseFare":{"amount":808.01,"currency":"USD","double":808.01,"currencyCode":"USD"},"totalFare":{"amount":858.23,"currency":"USD","double":858.23,"currencyCode":"USD"},"totalBaseFare":808.01,"localeTotalBaseFare":"$808","localeTotalFlightTaxes":"$43","totalFlightTaxes":43.22,"localeTotalFlightFare":"$858","localeTotalFees":"$7","localeTotalFlightTaxesAndFees":"$50","totalFees":7.0,"totalTaxesAndFees":{"amount":50.22,"currency":"USD","double":50.22,"currencyCode":"USD"},"flightFare":{"currencyCode":"USD","basePrice":808.01,"taxes":43.22}},"flightId":"39","showFareDisplayName":false,"fareDisplayName":"Published","firstBagFreeAirline":false,"operatedByFeeDisplayFeatureEnabled":false,"hasFare":true,"localeFormatAvgBasePrice":"$808","localeFormatAvgTotalPrice":"$858","stops":2,"bargainFare":false,"fareName":"published","selectedFlightPara":"39:39:FLTIStr","fareTypeCode":"P","airProviderId":2,"ccfeeAirline":"","displayLCCFareName":false,"noOfTicketsLeft":1,"seatPreview":true,"localeFormatAvgTotalTaxesAndFees":"$50","priceIllegal":false,"fareTypeValue":"1","showOBFeeMessageForModule":false,"completeTrip":false,"hasAirlineWithBagFee":false,"hasAirlineWithNoBagFee":false,"isABestTrip":true,"carrierList":["DL","AA"],"isFirstBagFreePos":true}, ...so on
json_decode takes a second parameter to return data as an associative array instead of objects. This will solve your problem. $json_array = json_decode($string,true); // returns 'normal' php array. $json = json_decode($string); // returns php object hierarchy
http://json.parser.online.fr/ reports that you data ends unexpectedly. Do you actually have the real data? Or if is it wrong, how did you generate it? There might be errors in the generation script cause it is not complete... There seems to be a misplaced character at the end. Instead of a comma ",", it should be a closing array "]"
You did not say WHY json_decode isn't working. If the JSON is too big to post here just use pastebin or something alike. I assume the reason it's not working is because you are exceeding the memory allowance for PHP, you can work around this by increasing the max memory PHP can use, eg: ini_set('memory_limit','16M'); However I wouldn't recommend doing this if this code is going to be ran by a large amount of users. Maybe if you give us some context we can give you an alternative solution which bypasses the need of json_decode.