'PHP recognizes array, that comes from file_get_contents() as string, though it is in right format

I recieve information with file_get_contents() and assign it to var like this:

$values = array();
$values = trim(file_get_contents($newurl));
echo gettype($values); // will show "string"

When i echo $values, i see that it is a string like:

[["EUR", "80"],["TRY", "50"],["USD", "40"],["GBP", "60"]];

And gettype($values) also shows "string" instead of array. But if i do

$values = [["EUR", "80"],["TRY", "50"],["USD", "40"],["GBP", "60"]];
echo gettype($values); // will show "array"

It will show me that $values is an array.

How can i tell php that trim(file_get_contents($newurl)) is an array, not a string?



Solution 1:[1]

1 either use the web-style parameter encoding

$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

2 use the explode functions

$string = 'Hello World';
$arr = str_split($string, 3);
print_r($arr);
//Array ( [0] => Hel [1] => lo [2] => Wor [3] => ld )

3 use json ( favoured since you can have assiocative arrays/objects parsed from there

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));

for 1 and 2 you will have to apply other tricks since this won't easily work recursive

Solution 2:[2]

You can add a function which test if it's a json string :

function isJsonString($ent){
if(!is_string($ent))
return false;
json_decode($ent);
return json_last_error() === JSON_ERROR_NONE;
}

and then, test :

if(isJsonString($values))
$values = json_decode($values); // --> stdObject 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Generic User
Solution 2 svgta