Can't unserialize a string in php - php
Yes, i know. I see a lot of questions about it.
But no one works for me until now.
I have a blog in wordpress who use serialized data for store some custom fields.
It works great, but when i moved all the blog to another folder, all serialized data gonne from wordpress (but it stills in the database)
So, wordpress don't detect it.
Now... i'm figthing with the code to know why isn't working.
At the end... i just thinked, well, i gonna do a code for get the serialized data and it will work.
Now i'm lost, i have this:
$data = 'a:7:{s:4:"zoom";s:2:"18";s:8:"latitude";s:8:"41.37233";s:9:"longitude";s:7:"1.04283";s:11:"address_one";s:16:"Finca Riudabella";s:11:"address_two";s:33:" s/n - 43430 Vimbodí (Tarragona)";s:3:"pin";s:77:"http://espaciosparaeventos.es/wp-content/uploads/2012/02/fincas.png";s:6:"bg_img";s:0:"";}';
$data = "a:7:{s:4:1}";
$data = trim($data);
var_dump($data);
var_dump(unserialize($data));
I tried with an original serialized string from the database (the fisrt line) and returns false and a error.
I done one a little bit simple, and say the same.
My error is:
Notice: unserialize() [function.unserialize]: Error at offset 5 of 11 bytes in C:\xampp\htdocs\unser.php on line 6
bool(false)
So, i don't know why i can't get data from the string!
I tried this tool http://unserialize.net/serialize and my data work just as expected :\ i need to do something else?
$broken_data = 'a:7:{s:4:"zoom";s:2:"18";s:8:"latitude";s:8:"41.37233";s:9:"longitude";s:7:"1.04283";s:11:"address_one";s:16:"Finca Riudabella";s:11:"address_two";s:33:" s/n - 43430 Vimbodí (Tarragona)";s:3:"pin";s:77:"http://espaciosparaeventos.es/wp-content/uploads/2012/02/fincas.png";s:6:"bg_img";s:0:"";}';
$data = serialize(
array(
"zoom" => "18",
"latitude" => "41.37233",
"longitude" => "1.04283",
"address_one"=>"Finca Riudabella",
"address_two"=>" s/n - 43430 Vimbodí (Tarragona)",
"pin"=>"http://espaciosparaeventos.es/wp-content/uploads/2012/02/fincas.png",
"bg_img"=> ""
)
);
// The right data
var_dump($data);
// Your data.
var_dump($broken_data);
var_dump(unserialize($data));
As you can see the serialization of $data is correct.
The serialized $broken_data seems to have incorrect string length at "pin".
In $broken_data it's stated to be 77 characters (s:77) but in reality it's 67 characters long (s:67)
I ran into this exact same problem recently and spent countless hours finding a way to restore the bad data. I walked through every function and line of code in the Spyropress theme, until it led me to page after page of functions inside WordPress, and finally leading me to understand that the maybe_unserialize() was failing.
That led me on a quest to figure out why, where I stumbled across a few threads like this one, that pointed out how the string counts could be off. It turns out that a find/replace had been performed on the data throughout the entire database, ruining tons of pages built with a theme.
In my case, I had to automate a "fix", and I posted my code in another thread. I'm not sure if better to post here or just link there, so I'm linking. You can see my code to "fix" serialized data here:
Handy code to automatically fix broken serialized data string counts.
My solution works with large datasets, containing HTML/CSS, escaped double quotes, newlines, and tons of special characters. I thought it might help those who find this page before the other one (like I did).
Cheers!
You're assigning data twice.
First assignment
$data = 'a:7:{s:4:"zoom";s:2:"18";s:8:"latitude";s:8:"41.37233";s:9:"longitude";s:7:"1.04283";s:11:"address_one";s:16:"Finca Riudabella";s:11:"address_two";s:33:" s/n - 43430 Vimbodí (Tarragona)";s:3:"pin";s:67:"http://espaciosparaeventos.es/wp-content/uploads/2012/02/fincas.png";s:6:"bg_img";s:0:"";}';
It fails on this: s:77:"http://espaciosparaeventos.es/wp-content/uploads/2012/02/fincas.png"; but as you've may noticed length of provided url is 67, when you manually change it to 67, and use: var_dump( unserialize( $data)); You'll get this:
array(7) {
["zoom"]=>
string(2) "18"
["latitude"]=>
string(8) "41.37233"
["longitude"]=>
string(7) "1.04283"
["address_one"]=>
string(16) "Finca Riudabella"
["address_two"]=>
string(33) " s/n - 43430 Vimbodí (Tarragona)"
["pin"]=>
string(67) "http://espaciosparaeventos.es/wp-content/uploads/2012/02/fincas.png"
["bg_img"]=>
string(0) ""
}
How it got changed? I don't know, there doesn't seem to be special characters, maybe class implementing Serializable provides wrong string length for URL.
Second assignment
$data = "a:7:{s:4:1}";
This is just wrong, declaring array with 7 items, providing just one... And that one is string that is supposed to have length 4 ("str1") and instead providing just 1... This just shouldn't and cannot work.
Related
PHPChart won't accept variables within data array
I've searched everywhere for an answer to this, and I truly do hate asking what is probably a really simple question, but I am lost. This is the code I'm using to display a pie cart ... $s1 = array( array('Carpets',235000), array('Vinyl',35069), array('LVT',36911), array('Laminate',5243.97) ); $pc = new C_PhpChartX(array($s1),'chart1'); $pc->set_grid(array('drawBorder'=>true, 'drawGridlines'=>false, 'background'=>'#ffffff', 'shadow'=>false)); $pc->set_axes_default(array()); $pc->set_series_default(array( 'renderer'=>'plugin::PieRenderer', 'rendererOptions'=>array('showDataLabels'=>true))); $pc->set_legend(array('show'=>true, 'rendererOptions'=> array('numberRows'=> 1), 'location'=> 's')); $pc->draw(400,400); The chart works fine like this for testing purposes, but when I try and replace the data inside the data array with variables, no chart appears. I think it may be to do with the way the data in the array is being passed to the JavaScript, but I am not skilled enough to fix. The data is in variables ... $cTotal, $vTotal, $lTotal & $laTotal I have echoed these and can confirm they are just producing an integer. I have tried ... $s1 = array( array('Carpets',$cTotal), array('Vinyl',$vTotal), array('LVT',$lTotal), array('Laminate',$laTotal) ); As well as using "" and "{}", but to no avail.
OK, so I figured it out. For some reason when I used ... $cTotal= $dataLabel['carpet']; It echoed 236987. But didn't work. However, had a last minute thought and physically forced it to be an integer with .. $cTotal= (int)$dataLabel['carpet']; ... and it worked. I thought PHP was clever enough to figure that out for itself!
PHP unserialize() Error at Offset [duplicate]
This question already has answers here: How to repair a serialized string which has been corrupted by an incorrect byte count length? (17 answers) Closed 9 years ago. The exact error I am getting is: ErrorException [ Notice ]: unserialize(): Error at offset 5 of 59 bytes The serialized data returned from a TEXT field in MySQL is (Encoding: utf8, Engine: InnoDB): a:1:{s:12:"display_name";s:6:"Foo";} After unserializing the output is: array(1) { [0]=> bool(false) } I am expecting something like this: array(1) { ["display_name"]=> string(6) "Foo" } I am using FuelPHP 1.6.1, PHP 5.4.10, MySQL 5.5.29, InnoDB 1.1.8 on Mac OS 10.8.4. Some of the serialized entries work on unserialize while others don't, if I copy one that works and paste into one that does not it shows the same error. I believe its a character issue and I have tried to encode into utf8, urlencode, and stripslashes but nothing seems to work. Any help is appreciated! Update The serialized string had a type, I did this when pasting it here for privacy to the actual display name. Here is the actual string: a:1:{s:12:"display_name";s:3:"Foo";} Thanks to #robw for pointing this out. Update & Answer I am running the serialized data through html_entity_decode() now as such: $unserialized = unserialize(html_entity_decode($serialized, ENT_QUOTES)); Thank you for the help and advice!
Your problem is here: s:6:"Foo" Foo is not 6 characters long... so that will never parse as expected. Try: s:3:"Foo" PS: This looks like you edited data in MySQL, then when your application tried to parse it, it errored out. You should never edit a serialized value in the database unless you're 100% sure you've modified the LENGTH in accordance to the TYPE and VALUE.
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
Why is constructing a URL with a mysql entry in PHP giving me a different String?
I'm writing some code to look at PTO assignment data, and noticed a strange problem where the URL didn't work when I generated it from my database entry, but did work when I entered the same string manually. When I echo them both strings look the same exactly, but when I equate them they are different. Is there some kind of hidden character or something with the encoding I can't see, and if so how do I fix it? I'm running the code using WAMPSERVER. $pto = "assignments.uspto.gov/assignments/q?db=pat&reel="; $row = mysql_fetch_assoc($result); $ReelFrame = $row['ReelFrame']; // Should be "007358/0006" and looks to be correct. $reelframearray = explode("/",$ReelFrame); $gourla = $pto . $reelframearray[0] . "&frame=". $reelframearray[1]; $gourl = "assignments.uspto.gov/assignments/q?db=pat&reel=007358&frame=0006"; echo "$gourla <br>"; echo "$gourl <br>"; if ($gourl === $gourla){ echo "same string"; } else { echo "different"; } This is what the results look like: assignments.uspto.gov/assignments/q?db=pat&reel=007358&frame=0006 assignments.uspto.gov/assignments/q?db=pat&reel=007358&frame=0006 different I've narrowed it down to the mysql entry since replacing that with this: $ReelFrame = "007358/0006"; Makes the strings the same. Thanks for any help. The column for ReelFrame is a VARCHAR if that makes any difference.
please try to var_dump() your both variables instead of echoing them - maybe there are some leading/trailing whitespaces, linebreaks or something like that. EDIT: just as a note: you realy shouldn't save multiple values in one database-coumn. if ReelFrame consits of two values, make two colums out of it: Reel and Frame - and don't use charchar for this, it looks like they should be ints (and that will avoid you from saving whitespaces linebreaks or something like that accidentally)
The first thought that comes to my mind is \n character. Try this: $ReelFrame = trim($row['ReelFrame']);
I tried the trim() suggestion, but it doesn't seem to work. I'm not sure what kind of character it is inserting, but I guess trim isn't removing it. I just tried the var_dump, and it does show the strings are different lengths though nothing else looks different. vardump of a ReelFrame entity compared with manual string: string(20) "007358/0006" string(11) "007358/0006" likewise for the final string: string(81) "assignments.uspto.gov/assignments/q?db=pat&reel=007358&frame=0006" string(72) "assignments.uspto.gov/assignments/q?db=pat&reel=007358&frame=0006" trim() doesn't seem to make any difference on the entity so it's still showing 20. Are there any other invisible characters that trim might miss?