如何使用PHP修复未通过GET命令返回结果的API
使用who is my representative API(whoismyrepresentative.com),get命令不会呈现索引页上请求zipcode的输入字段的结果。语法是否不正确,是否需要回显命令 我创建的索引页:如何使用PHP修复未通过GET命令返回结果的API,php,api,Php,Api,使用who is my representative API(whoismyrepresentative.com),get命令不会呈现索引页上请求zipcode的输入字段的结果。语法是否不正确,是否需要回显命令 我创建的索引页: <section class="form-one"> <form action="search-results.php" method="post"> <label for="zipcode"> Input Zipcode</
<section class="form-one">
<form action="search-results.php" method="post">
<label for="zipcode"> Input Zipcode</label>
<input id="zipcode" type="number" name="zip" size="5">
<input type="submit" name="">
</form>
</section>
输入Zipcode
Search-Results.php页面,我在其中调用GET命令:
<?php
file_get_contents('https://whoismyrepresentative.com/getall_mems.php?zip=&output=json'.$_GET['zip'].'php?zip=&output=json …');
/*echo $_GET["https://whoismyrepresentative.com/getall_mems.php?zip=&output=json …"];*/
?>
命令应输出json。这将起作用:
file_get_contents('https://whoismyrepresentative.com/getall_mems.php?zip=' . $_GET['zip'] . '&output=json');
您将表单设置为发出post请求。 您可以通过两种方式修复代码
使用php
cURL
<?php
$ch = curl_init('https://whoismyrepresentative.com/getall_mems.php?zip=' . $_POST['zip']);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/json'
);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
//execute
$result = curl_exec($ch);
//close connection
curl_close($ch);
echo $result;
?>
查看您的实时站点和API后,您的问题归结为两个错误 要使用GET,您需要更新HTML表单方法以获取-
<section class="form-one">
<form action="search-results.php" method="get">
<label for="zipcode"> Input Zipcode</label>
<input id="zipcode" type="number" name="zip" size="5">
<input type="submit" name="">
</form>
</section>
您将$\u GET放在了错误的位置,没有查看API,我假设它需要是
file\u GET\u contents('https://whoismyrepresentative.com/getall_mems.php?zip='.$_GET['zip'.&output=json')
我尝试了你的代码也没有用,我让这个页面为参考目的而激活:更改你的表单方法以获取
,或者将你的$\u get['zip']
更新为$\u POST['zip']
Abdur Rahman建议,不幸的是,这也不能解决问题。我尝试了几次你的代码,但都没有成功,我也尝试了,手动输入无效…@Jay我已经检查了你的实时代码。它给我带来了一些解析错误。“解析错误:语法错误,意外的‘谢谢,我尝试了几次,但都不起作用:(我想知道是不是url中的‘zip=’导致了问题。‘zip’也是表单的name属性。$ch=curl\u init('zip')”https://whoismyrepresentative.com/getall_mems.php?zip=“.$\u GET['zip']”;
应该是$ch=curl\u init('https://whoismyrepresentative.com/getall_mems.php?zip=“.$\u GET['zip'])
我试过了,但没用…这是给会员的链接:?没有数据…谢谢!我知道我的url格式有问题。我有一段时间没用php了,所以我不知道我必须分配url和回送文件内容。太吸引人了!我是多任务的,但我应该早点找到它。哈哈,如果这样的话it’它已修复。请确保标记正确答案。:)
<?php
$json_rep = file_get_contents('https://whoismyrepresentative.com/getall_mems.php?zip='.$_GET['zip'].'&output=json');
$rep_array = json_decode($json_rep);
var_dump($rep_array);
?>