How to deserialize this string into a PHP array of key => value pairs?

13,586

Solution 1

You can do this by unserializing the data (using unserialize()) and then iterating through it:

$fonts = array();

$contents = file_get_contents('http://phat-reaction.com/googlefonts.php?format=php');
$arr = unserialize($contents);

foreach($arr as $font)
{
    $fonts[$font['css-name']] = $font['font-name'];
}

Depending on what you're using this for, it may be a good idea to cache the results so you're not fetching external data each time the script runs.

Solution 2

Use unserialize(): http://www.php.net/unserialize

Share:
13,586

Related videos on Youtube

RegEdit
Author by

RegEdit

Updated on June 04, 2022

Comments

  • RegEdit
    RegEdit almost 2 years

    I'm calling the script at: http://phat-reaction.com/googlefonts.php?format=php

    And I need to convert the results into a PHP array format like the one I'm currently hard coding:

    $googleFonts = array(
        "" => "None",
        "Abel"=>"Abel",
        "Abril+Fatface"=>"Abril Fatface",
        "Aclonica"=>"Aclonica",
        etc...
        );
    

    The php returned is serialized:

    a:320:{
        i:0;
        a:3:{
            s:11:"font-family";
            s:32:"font-family: 'Abel', sans-serif;";
            s:9:"font-name";
            s:4:"Abel";
            s:8:"css-name";
            s:4:"Abel";
            }
        i:1;
        a:3:{
            s:11:"font-family";
            s:38:"font-family: 'Abril Fatface', cursive;";
            s:9:"font-name";
            s:13:"Abril Fatface";
            s:8:"css-name";
            s:13:"Abril+Fatface";
            }
    
            etc...
    

    How can I translate that into my array?

    • mario
      mario over 12 years
      That's quite simply PHPs serialization format. Use unserialize() to turn it back.