Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

php

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?

like image 907
RegEdit Avatar asked Dec 17 '11 18:12

RegEdit


People also ask

What does => mean in PHP array?

It means assign the key to $user and the variable to $pass. When you assign an array, you do it like this. $array = array("key" => "value"); It uses the same symbol for processing arrays in foreach statements. The '=>' links the key and the value.

Which array has pair of value and key in PHP?

Associative arrays - Arrays with named keys.

What is unserialize function in PHP?

The unserialize() function converts serialized data back into actual data.

What is key in associative array in PHP?

Traversing the Associative Array Example: In Associative arrays in PHP, the array keys() function is used to find indices with names provided to them, and the count() function is used to count the number of indices.


2 Answers

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.

like image 168
Tim Cooper Avatar answered Oct 06 '22 05:10

Tim Cooper


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

like image 39
duri Avatar answered Oct 06 '22 06:10

duri