Home > front end >  PHP recognizes array, that comes from file_get_contents() as string, though it is in right format
PHP recognizes array, that comes from file_get_contents() as string, though it is in right format

Time:02-18

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?

CodePudding user response:

Try this:

$values = json_decode(trim(file_get_contents($newurl)), 1);
echo gettype($values); // Array

CodePudding user response:

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

CodePudding user response:

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 
  • Related