问题
I have a php script, then I run it line by line.
I run this line:
$ip = trim(shell_exec("dig +short myip.opendns.com @resolver1.opendns.com"));
I got : 50.198.81.174
Then I run the next line:
$php_info = trim(shell_exec("curl ipinfo.io/".$ip));
I got
"""
{\n
"ip": "50.198.81.174",\n
"hostname": "50-198-81-174-static.hfc.comcastbusiness.net",\n
"city": "Braintree",\n
"region": "Massachusetts",\n
"country": "US",\n
"loc": "42.2038,-71.0022",\n
"org": "AS7922 Comcast Cable Communications, Inc.",\n
"postal": "02184"\n
}
"""
I'm trying to access the result in it, for example the city
echo ($php_info['city']);
I couldn't. :(
How do I properly access them?
回答1:
You are using the wrong command. You should use exec();
It has a built-in argument for outputting the results into an array so that you dont have to do that yourself with a bunch of code. Then you can just parse the array element that has the info you want.
<?php
$info = exec("curl ipinfo.io/8.8.8.8",$arrInfo);
print_r($arrInfo);
//outputs
Array ( [0] => { [1] => "ip": "8.8.8.8", [2] => "hostname": "google-public-dns-a.google.com",
[3] => "city": "Mountain View",
[4] => "region": "California",
[5] => "country": "US",
[6] => "loc": "37.3860,-122.0838",
[7] => "org": "AS15169 Google Inc.",
[8] => "postal": "94040" [9] => } )
OR you can just use JSON_DECODE and continue to use shell_exec(); This will get you the exact values in the array.
<?php
$info = shell_exec("curl ipinfo.io/8.8.8.8");
print_r(json_decode($info,true));
?>
//output
Array ( [ip] => 8.8.8.8 [hostname] => google-public-dns-a.google.com
[city] => Mountain View [region] => California
[country] => US
[loc] => 37.3860,-122.0838
[org] => AS15169 Google Inc. [postal] => 94040 )
Json_decode with the true flag will output it in to an associative array.
回答2:
i think this will help you. To access each specification you just need use index of list
<?php
$str = '"""
{\n
"ip": "50.198.81.174",\n
"hostname": "50-198-81-174-static.hfc.comcastbusiness.net",\n
"city": "Braintree",\n
"region": "Massachusetts",\n
"country": "US",\n
"loc": "42.2038,-71.0022",\n
"org": "AS7922 Comcast Cable Communications, Inc.",\n
"postal": "02184"\n
}
"""';
$find = array('"""', '\n', '{', '}');
$str = str_replace($find, '', $str);
$str = str_replace('",', "-*-", $str);
$str = explode("-*-", $str);
$list[] = "";
for($i=0;$i<count($str);$i++)
{
$str_temp = str_replace('"', '', $str);
$str_temp = explode(":", $str_temp[$i]);
$str_temp[0] = str_replace("\n", "", $str_temp[0]);
$str_temp[1] = str_replace("\n", "", $str_temp[1]);
$list[trim($str_temp[0])] = $str_temp[1];
}
echo $list['city']."<hr>";
echo $list['country']."<hr>";
echo $list['region']."<hr>";
echo $list['org']."<hr>";
var_dump($list);
For example $list['city'] will return the name of city.
来源:https://stackoverflow.com/questions/32976328/how-can-i-access-the-data-i-got-back-from-shell-exec