如何使用curl GET而不是POST

时间:2013-03-18 21:08:46

标签: php curl

我正在使用curl来打印来自网址的回复。到目前为止我的代码看起来像这样:

<?php
    $street = $_GET['street'];
    $city = $_GET['city'];
    $state = $_GET['state'];
    $zip = $_GET['zip'];

    $url = 'http://eligibility.cert.sc.egov.usda.gov/eligibility/eligibilityservice';
    $query = 'eligibilityType=Property&requestString=<?xml version="1.0"?><Eligibility xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="/var/lib/tomcat5/webapps/eligibility/Eligibilitywsdl.xsd"><PropertyRequest StreetAddress1="'.$street.'" StreetAddress2="" StreetAddress3="" City="'.$city.'" State="'.$state.'" County="" Zip="'.$zip.'" Program="RBS"></PropertyRequest></Eligibility>';
    $url_final = $url.''.$url_query;

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$query);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $return = curl_exec ($ch);
    curl_close ($ch);

    echo $return;

?>

我知道唯一明显的问题是被查询的服务器使用GET而不是POST。这种方法有GET个替代方案吗?

5 个答案:

答案 0 :(得分:24)

curl_setopt($ch, CURLOPT_POST, 0);

Curl默认使用GET。您将其设置为POST。如果您需要使用curl_setopt($ch, CURLOPT_HTTPGET, 1);

,可以覆盖它

答案 1 :(得分:3)

使用file_get_contents()函数
file_get_contents

curl_setopt($ch, CURLOPT_HTTPGET, 1);

答案 2 :(得分:1)

使用

curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => "http://yourlink.com",
CURLOPT_USERAGENT => 'Codular Sample cURL Request'));

答案 3 :(得分:1)

这些年来,没有人给出正确的答案;构建查询字符串的方法是将http_build_query()与数组一起使用。这会自动转义所有内容并返回一个简单的字符串。

$xml = '<?xml version="1.0"?><Eligibility xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="/var/lib/tomcat5/webapps/eligibility/Eligibilitywsdl.xsd"><PropertyRequest StreetAddress1="'.$street.'" StreetAddress2="" StreetAddress3="" City="'.$city.'" State="'.$state.'" County="" Zip="'.$zip.'" Program="RBS"></PropertyRequest></Eligibility>';
$data = [
    "eligibilityType" => "Property",
    "requestString" => $xml
];
$query = http_build_query($data);
$url .= "?$query";

答案 4 :(得分:0)

您在网址中缺少问号。 应该像:

$query = '?eligibilityType=Property&...';

此外,您网址中的XML需要编码,例如在PHP中使用urlencode()函数。