如何使用PHP解析序列化数据?

时间:2017-05-03 04:49:25

标签: php parsing serialization

这是我的序列化数据的一个例子:

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";}

我希望能够使用PHP解析它并显示如下值:

  • profile_first_name:Ben
  • profile_last_name:权力
  • profile_state:AL

我知道我需要像这样反序列化它:

$unserialize = unserialize($data);

但我在使用PHP解析数组时遇到问题。我不断收到“为foreach()提供的无效参数”错误以及错误的数组输出。

1 个答案:

答案 0 :(得分:4)

这就是你要找的东西

    <?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);   

您已经腐蚀的字符串已损坏,因此您需要先修复它然后取消序列化

<强>输出

    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
    )

输出: - https://eval.in/785908