英文:
API code error 400 - when trying to call API in php
问题
I'm trying to call an API in PHP; however, it comes up with error 400, even though if I try to do the same API call in Python, it works fine.
This is the PHP code I'm trying to execute; the echoes are just to see what is going on:
if (isset($_POST['stock']))
{
$ticker = $_POST['stock'];
echo $ticker;
$json = file_get_contents($url);
echo $json;
$data = json_decode($json, true);
echo $data;
print_r($ticker . " price: " . $data);
}
The URL is:
$url = "https://api.twelvedata.com/price?symbol=" . $ticker . "&apikey=" . $TDKEY;
With "ticker" and "TDKEY" being variables. I think this is correct; there's nothing I can see that's wrong here.
And the output is:
AAPL{"code":400,"message":"There is an error in the query. Please check your query and try again. If you're unable to resolve it, contact our support at https://twelvedata.com/contact/customer","status":"error"}ArrayAAPL price: Array
英文:
I'm trying to call an api in php however it comes up with error 400 even though if i try to do the same api call in python it works fine.
This is the php code I'm trying to execute the echoes are the just to see what is going on:
if (isset($_POST['stock']))
{
$ticker = $_POST['stock'];
echo $ticker;
$json = file_get_contents($url);
echo $json;
$data = json_decode($json,true);
echo $data;
print_r($ticker." price: ".$data);
}
the url is:
$url = "https://api.twelvedata.com/price?symbol=".$ticker."&apikey=".$TDKEY;
with ticker and tdkey being variables, I think this is correct there's nothing I can see that's wrong here.
and the output is:
AAPL{"code":400,"message":"There is an error in the query. Please check your query and try again. If you're unable to resolve it contact our support at https://twelvedata.com/contact/customer","status":"error"}ArrayAAPL price: Array
答案1
得分: 0
Your code should be:
if (isset($_POST['stock']))
{
$ticker = $_POST['stock'];
$url = "https://api.twelvedata.com/price?symbol=" . $ticker . "&apikey=" . $TDKEY;
$json = file_get_contents($url);
$data = json_decode($json, true);
echo $ticker . " price: ";
print_r($data);
}
else
{
throw Exception("Ticker is not set");
}
英文:
Where are you setting the URL? Your code shows that the ticker variable is only set in the if statement, but it is never passed to the URL variable - Therefore $url = "https://api.twelvedata.com/price?symbol=".$ticker."&apikey=".$TDKEY;
cannot be valid, as ticker is seemingly not set at the time of URL being intialised
Additionally, using print_r($ticker)
is also going to throw an error, it's a variable, not an array
Your code needs to become
if (isset($_POST['stock']))
{
$ticker = $_POST['stock'];
$url = "https://api.twelvedata.com/price?symbol=".$ticker."&apikey=".$TDKEY;
$json = file_get_contents($url);
$data = json_decode($json,true);
echo $ticker." price: ";
print_r($data);
}
else
{
throw Exception("Ticker is not set");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论