使用 PHP 从 API 中仅获取一个值

Fetch only one value from API with PHP

我最近一直在尝试从financialmodelingprep.com获取股票数据,我成功找到了代码;

set_time_limit(0);

$url_info = "https://financialmodelingprep.com/api/v3/stock/real-time-price/AAPL";

$channel = curl_init();

curl_setopt($channel, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($channel, CURLOPT_HEADER, 0);
curl_setopt($channel, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($channel, CURLOPT_URL, $url_info);
curl_setopt($channel, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($channel, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($channel, CURLOPT_TIMEOUT, 0);
curl_setopt($channel, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($channel, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($channel, CURLOPT_SSL_VERIFYPEER, FALSE);

$output = curl_exec($channel);

if (curl_error($channel)) {
    return 'error:' . curl_error($channel);
} else {
    echo $output;
}

此代码输出:{ "symbol" : "AAPL", "price" : 324.83 } 我想知道如何只获取 "price" 数字 (324.83) 并将其存储在 php 变量中。 提前致谢。

您得到的输出是 json 格式。使用 json_decode() 将其转换为数组,然后您可以从数组中提取任何您想要的值:

$array = json_decode($output, true);
var_dump($array['price']);