How to properly count json contents? - php

This is my json
[
{"id":"1736375","first_name":"fname1","force_first_name":"ffname1","last_name":"lname1","thumb_path":"","path":"img\/profiles\/generic\/gray.png"},
{"id":"1607011","first_name":"fname2","force_first_name":"ffname2","last_name":"lname2","thumb_path":"","path":"img\/profiles\/generic\/gray.png"},
{"id":"1607012","first_name":"fname3","force_first_name":"ffname3","last_name":"lname3","thumb_path":"","path":"img\/profiles\/generic\/gray.png"}
]
I am trying to count the number of sets inside [ ]
I tried using this
echo count(json_decode($people, true));
I get zero (0) result.
How can I properly count it.
Thanks
=== EDIT FOR THE SAKE OF FUTURE VIEWER ===
it is the json that is malformed as stated by several comments, the code i wrote above is how I see it but the real content of the json was this
string(3)"
[
{"id":"1736375","first_name":"fname1","force_first_name":"ffname1","last_name":"lname1","thumb_path":"","path":"img\/profiles\/generic\/gray.png"},
{"id":"1607011","first_name":"fname2","force_first_name":"ffname2","last_name":"lname2","thumb_path":"","path":"img\/profiles\/generic\/gray.png"},
{"id":"1607012","first_name":"fname3","force_first_name":"ffname3","last_name":"lname3","thumb_path":"","path":"img\/profiles\/generic\/gray.png"}
]"
as pointed out by #dontpanic, a string will always return 1 which is what I get. I reported the problem to the developer and luckily they corrected the json response and now it is working OK.
Thanks to all who made an effort to comment leading to the discovery of the problem.

Using this exact code I get the desired output of 3, as well as the other comments above. I'd recommend debugging the $people variable to ensure that it is remaining a json object all the way through until your echo statement, as it is quite possible it is either being malformed or changed all together, therefore giving you unexpected results.
<?php
$people = <<<EOD
[
{"id":"1736375","first_name":"fname1","force_first_name":"ffname1","last_name":"lname1","thumb_path":"","path":"img\/profiles\/generic\/gray.png"},
{"id":"1607011","first_name":"fname2","force_first_name":"ffname2","last_name":"lname2","thumb_path":"","path":"img\/profiles\/generic\/gray.png"},
{"id":"1607012","first_name":"fname3","force_first_name":"ffname3","last_name":"lname3","thumb_path":"","path":"img\/profiles\/generic\/gray.png"}
]
EOD;
echo count(json_decode($people, true));

Try:
echo count(json_decode(stripslashes($people), true));

Related

PHP Json Values from Keys not being parsed from External API Call

I am trying to make an external API call to fetch JSON data and return it within my web app.
Here is what the data looks like from the API call:
JSON returned from URL:
{
"results":[
{
"name":"Company1",
"ProviderName": "ProviderName1",
"ProviderLogo": "/images/some_image1.jpg",
"GetURL": "/some_url_path",
"Costs": 10000.50
},{
"name":"Company2",
"ProviderName": "ProviderName2",
"ProviderLogo": "/images/some_image2.jpg",
"applyURL": "/some_url_path",
"Costs": 12000.50
}]
}
Since I am using PHP, I am using the following code:
$api_data = file_get_contents('MY URL');
// Had to use 'encoded_json()' since 'json_decode()' was initially returning NULL
$encoded_json = json_encode($api_data);
$decoded_json = json_decode($encoded_json);
// Now I want to get the specific values from the JSON result but nothing is being returned
// I tried using something like this but I'm not getting anything
foreach($decoded_json->results as $mydata)
{
echo 'Decoded Name: ' . $mydata->name . "\n";
}
Any help is greatly appreciated!
EDIT:
So this what was actually happening and I'm going to apologize to everyone in advance right now because I didn't include what was actually throwing the error off in the first place!
I used JSON Lint and put all of the API Json data that I was receiving and it showed me where the error was occurring.
Error:
"SomeCostUpper": $some_variable.rawUpperCost
I tested out my PHP code using valid JSON and was able to return the results without a problem.
Everyone, I'm really sorry for the confusion but thanks for your efforts!
$api_data = file_get_contents('MY URL');
You now have a string containing the data in that URL.
// Had to use 'encoded_json()' since 'json_decode()' was initially returning NULL
If json_decode returns NULL, then the string you had does not contain valid JSON.
$encoded_json = json_encode($api_data);
You now have a string representation of a string containing the data from the URL.
$decoded_json = json_decode($encoded_json);
And now you have reversed that, so you have your original string back.
foreach($decoded_json->results as $mydata)
It is a string. You can't do that.
You need to fix the data you are getting from MY URL.
Use a tool like JSON Lint, which will give you an error like:
Error: Parse error on line 7:
..."Costs": 10000.50, }, { "name": "Comp
----------------------^
Expecting 'STRING', got '}'
You have a rogue comma after the last entry in your object.
This is likely caused by generating JSON by mashing together strings or by writing it by hand. Avoid that. Use tools and libraries designed to generate JSON.
I don't know from which website you get that JSON data, but it isn't valid JSON, that is why json_decode() initially returned NULL. There are 2 commas (each costs value has one) that shouldn't be there.
You "fixed" that by using first json_encode() and then json_decode() on the JSON data returned from the API call. You might think that that fixed your problem but no, if you take a look at what is inside $decoded_json you will see that there isn't an object or an array which you can use.
That means that when you try to do
foreach($decoded_json->results as $mydata)
{
echo 'Decoded Name: ' . $mydata->name . "\n";
}
It fails because it cannot iterate over the 'string' inside $decoded_json.
If you had turned on error reporting you would have seen the following errors:
E_NOTICE : type 8 -- Trying to get property of non-object -- at line n
E_WARNING : type 2 -- Invalid argument supplied for foreach() -- at line n
the json is ok, you don't need to encode and then decode again...
just do:
$api_data = file_get_contents('MY URL');
$decoded_json = json_decode($api_data );
foreach($decoded_json->results as $mydata)
{
echo 'Decoded Name: ' . $mydata->name . "\n";
}
Your JSON data is not valid. Here is the valid JSON structure.
Remove the ',' from the last elemp "Costs": "10000.50" and use double quote for the value as "10000.50".

Get json string elements

I am using a astrology API which sends an json string as response to the query. But i have been trying for long to convert it into json and retrieve different items from the response string. Here is the example of the response:
{"ashtakoota":{"status":true,"received_points":26},"manglik":{"status":true,"male_percentage":13.25,"female_percentage":13.75},"rajju_dosha":{"status":false},"vedha_dosha":{"status":false},"conclusion":{"match_report":"Marriage between the prospective bride and groom is highly recommended. The couple would have a long-lasting relationship, which would be filled with happiness and affluence."}}
I am using php script so i tried the following code :
$json = json_decode($res1, true);
TRY 1 --> echo array_values($json[1]);
TRY 2 --> echo $json.ashtakoota.status;
TRY 3 --> echo $res1.ashtakoota.status;
But the output is always blank. I doubt that $json is empty or the json response is not perfectly json.
PHP uses string keys for its arrays, which is what json_decode(...) returns. As such, you need to access them as:
echo $json['ashtakoota']['status'];
Which should then output true for your example JSON input.
The true parameter on json_decode will cause it to return an array, not an object. Your syntax for objects is also incorrect, it's not a dot, but rather -> that you need.
$json = json_decode($res1);
echo $json->ashtakoota->status;

Extracting value from JSON data in PHP

I have extracted data from another website which is in JSON format - here is what I extracted: http://sub7legends.net/crawler.php
I need to get the value of kills and deaths from this.
I tried json_decode() in php of this data but when I var_dump() the result it just says "NULL".
What can I do to extract the required data?
The link doesn't work for me. But if you have a normal json just like this one:
{"kills": "5", "deaths": "3"}
Then the json_decode() method should work.
Here would be a sample code snippet:
$json_you_got_from_the_server = '{"kills": "5", "deaths": "3"}';
$result = json_decode($json_you_got_from_the_server);
$kills = $result->kills;
$deaths = $result->deaths;
echo "You have ".$kills." kills and ".$deaths." deaths.";
I haven't tried it, but it should work. If it doesn't, then please comment and I will try something else.
the current json contents are not valid, try validating it first. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
That json in the link you have pasted has no proper ending scroll to the end and you will see. If this is the same thing that you wanted to parse then it will always return null.

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.

json_decode returns null with PHP, NFL API

For some reason json_decode is returning NULL with valid JSON.
The json is located here: http://www.nfl.com/liveupdate/scorestrip/scorestrip.json
I am getting the file contents of the page (file_get_contents) and then running json_decode on it.
Also tried stripslashes b/c of magic quotes.
Thanks in advance,
Phil
$json = file_get_contents('http://www.nfl.com/liveupdate/scorestrip/scorestrip.json');
var_dump(json_decode($json));
The empty array elements are invalid JSON, ie the multiple commas with no values between
["Thu","7:30","Final",,"BAL","6","PHI","13",,,"55424",,"PRE1","2011"]
^ Here ^ Here ^Here
You could try inserting empty strings between multiple commas (thanks hakre), ie
$json = preg_replace('/,(?=,)/m', ',""', $json);
// I'm dubious about this working, don't have PHP to test but it works in JS
I don't know if this messes up your ability to continue using the data though
I came the same conclusion as Phil, but it took me about 5 minutes longer. : )
However, I noticed a problem in his output... it is dropping a field.
I don't like doing this kind of pattern detection in RegEx, only because I think it is harder to maintain. In this case, I just run it through a while loop.
while (strpos($json,',,'))
{
$json = str_replace(',,',',"",', $json);
}
I'm sure Phil can come up with a proper RegEx, but this solution will maintain the right # of entries & their ordinal positions.
For anyone looking in 2014. The new feed data link should be:
http://www.nfl.com/liveupdate/scores/scores.json

Categories