问题
This is an example of my serialized data:
a:10:{s:7:"contact";s:1:"1";s:19:"profile_affiliation";s:23:"University, Inc.";s:18:"profile_first_name";s:3:"Ben";s:22:"profile_street_address";s:19:"8718 Tot Ave. S.";s:12:"profile_city";s:6:"Mobile";s:13:"profile_state";s:2:"AL";s:15:"profile_country";s:3:"USA";s:15:"profile_zipcode";s:5:"36695";s:18:"profile_home_phone";s:10:"2599494420";s:17:"profile_last_name";s:6:"Powers";}
I want to be able to parse through it with PHP and display the values like so:
- profile_first_name: Ben
- profile_last_name: Powers
- profile_state: AL
I know I need to unserialize it like so:
$unserialize = unserialize($data);
but I'm having trouble parsing the array with PHP. I keep getting "Invalid argument supplied for foreach()" errors and the incorrect array output.
回答1:
This is what you are looking for
<?php
$serialized = 'a:10:{s:7:"contact";s:1:"1";s:19:"profile_affiliation";s:23:"University, Inc.";s:18:"profile_first_name";s:3:"Ben";s:22:"profile_street_address";s:19:"8718 Tot Ave. S.";s:12:"profile_city";s:6:"Mobile";s:13:"profile_state";s:2:"AL";s:15:"profile_country";s:3:"USA";s:15:"profile_zipcode";s:5:"36695";s:18:"profile_home_phone";s:10:"2599494420";s:17:"profile_last_name";s:6:"Powers";}';
$fixed = preg_replace_callback(
'/s:([0-9]+):"(.*?)";/',
function ($matches) { return "s:".strlen($matches[2]).':"'.$matches[2].'";'; },
$serialized
);
$original_array=unserialize($fixed);
echo "<pre>";
print_r($original_array);
You serailized string is corrupted so you need to repair it first then unserialize it
output
Array
(
[contact] => 1
[profile_affiliation] => University, Inc.
[profile_first_name] => Ben
[profile_street_address] => 8718 Tot Ave. S.
[profile_city] => Mobile
[profile_state] => AL
[profile_country] => USA
[profile_zipcode] => 36695
[profile_home_phone] => 2599494420
[profile_last_name] => Powers
)
Output:- https://eval.in/785908
来源:https://stackoverflow.com/questions/43751303/how-can-i-parse-serialized-data-with-php