17

我很想使用 curl 打印来自 url 的返回。到目前为止,我的代码如下所示:

<?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替代品吗?

4

5 回答 5

26
curl_setopt($ch, CURLOPT_POST, 0);

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

于 2013-03-18T21:10:24.840 回答
4

使用 file_get_contents() 函数
file_get_contents

或者
curl_setopt($ch, CURLOPT_HTTPGET, 1);

于 2013-03-18T21:13:06.323 回答
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";
于 2018-03-03T17:37:37.420 回答
1

利用

curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => "http://yourlink.com",
CURLOPT_USERAGENT => 'Codular Sample cURL Request'));
于 2017-05-24T10:40:15.733 回答
0

您在 URL 中缺少问号。应该是这样的:

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

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

于 2013-03-18T21:10:19.617 回答