如何访问从 shell_exec 取回的数据?

How can I access the data I got back from shell_exec?

我有一个 php 脚本,然后我 运行 逐行编写它。

我运行这一行: $ip = trim(shell_exec("dig +short myip.opendns.com @resolver1.opendns.com"));

我得到了:50.198.81.174

然后我运行下一行:

$php_info = trim(shell_exec("curl ipinfo.io/".$ip));

我得到了

"""
{\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
}
"""

我正在尝试访问其中的结果,例如 city

echo ($php_info['city']);

我做不到。 :(

如何正确访问它们?

我想这会对你有所帮助。 要访问每个规范,您只需要使用列表索引

<?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);

例如 $list['city'] 将 return 城市名称。

您正在使用错误的命令。您应该使用 exec(); 它有一个内置参数,用于将结果输出到 数组 中,这样您就不必自己使用一堆代码来执行此操作。然后你可以只解析包含你想要的信息的数组元素。

<?php
$info = exec("curl ipinfo.io/8.8.8.8",$arrInfo);
print_r($arrInfo);

//输出

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] => } )

或者您可以只使用 JSON_DECODE 并继续使用 shell_exec();这将为您提供数组中的 exact 值。

<?php

$info = shell_exec("curl ipinfo.io/8.8.8.8");

print_r(json_decode($info,true));
?>

//输出

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 带有 true 标志会将其输出到关联数组。