我想从网址https://data-asg.goldprice.org/dbXRates/USD中获取数据
所以我写了以下代码
$curlSession = curl_init();
curl_setopt($curlSession, CURLOPT_URL, 'https://data-asg.goldprice.org/dbXRates/USD');
curl_setopt($curlSession, CURLOPT_BINARYTRANSFER, true);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);
$jsonData = json_decode(curl_exec($curlSession));
$item = $jsonData->items;
$date = $jsonData->date;
$gold_price = $item[0]->xauPrice;
echo "Gold price on ".$date." is ".$gold_price;
curl_close($curlSession);
但是由于某种原因,这不起作用。请检查
注意:尝试获取非对象的属性“项目” 第9行的C:\ xampp \ htdocs \ test.php
注意:试图获取非对象的属性“日期” 第10行的C:\ xampp \ htdocs \ test.php
注意:尝试获取非对象的属性“ xauPrice” 第11行的C:\ xampp \ htdocs \ test.php
从goldprice.org我们得到的是Gold-> USD-> OZ = 1,275.67。此值 我们正在使用上面的代码输出。但我需要黄金->美元-> g = 41.01 。请检查goldprice.org您将了解
答案 0 :(得分:3)
使用此:
$curlSession = curl_init();
curl_setopt($curlSession, CURLOPT_URL, 'https://data-asg.goldprice.org/dbXRates/USD');
curl_setopt($curlSession, CURLOPT_BINARYTRANSFER, true);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlSession, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curlSession, CURLOPT_SSL_VERIFYPEER, 0);
$output = curl_exec($curlSession);
$jsonData = json_decode($output);
var_dump($jsonData);
$item = $jsonData->items;
$date = $jsonData->date;
$gold_price = $item[0]->xauPrice;
echo "Gold price on ".$date." is ".$gold_price;
curl_close($curlSession);
您没有:
curl_setopt($curlSession, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curlSession, CURLOPT_SSL_VERIFYPEER, 0);
答案 1 :(得分:2)
您可以将响应转换为数组并访问所需的元素
$jsonData = json_decode(curl_exec($curlSession));
替换为
$jsonData = json_decode(curl_exec($curlSession), true);
参数true
会将对象转换为数组。
print_r($jsonData);
Array
(
[ts] => 1555669932973
[tsj] => 1555669926185
[date] => Apr 19th 2019, 06:32:06 am NY
[items] => Array
(
[0] => Array
(
[curr] => USD
[xauPrice] => 1275.67
[xagPrice] => 14.905
[chgXau] => 3.77
[chgXag] => -0.032
[pcXau] => 0.2964
[pcXag] => -0.2142
[xauClose] => 1271.9
[xagClose] => 14.937
)
)
)
答案 2 :(得分:1)
尝试一下:
<?php
$json = file_get_contents("https://data-asg.goldprice.org/dbXRates/USD");
$jsonData = json_decode($json);
$items = $jsonData->items;
$item = $items[0];
$date = $jsonData->date;
$gold_price = $item->xauPrice;
echo "Gold price on ".$date." is ".$gold_price;
答案 3 :(得分:1)
使用此:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://data-asg.goldprice.org/dbXRates/USD",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Cache-Control: no-cache",
"Postman-Token: 67666a77-d99b-c8fb-f202-5ae0003cfe31"
),
));
$response = curl_exec($curl);
$res = json_decode($response);
echo $res->date.' ';
$price = $res->items;
echo $price[0]->xauPrice;
$err = curl_error($curl);
curl_close($curl);