PHP 卷曲标头

Posted

技术标签:

【中文标题】PHP 卷曲标头【英文标题】:PHP curl headers 【发布时间】:2015-02-01 05:38:31 【问题描述】:

我不太擅长使用 php 和 cURL,通常我只是使用 javascript 或 C# 进行调用,但是我正在使用 wordpress,所以 C# 不可能,而且我在调用 url 中有一个 apikey,所以我是想知道我是否可以对此有所帮助。在 javascript 中,调用将是。

     var forecastOptions = 
        "cache":  false,
        "dataType":  "jsonp",
        "url":  callSite
    ;
    var forecastRequest = $.ajax(forecastOptions);

我这样做是为了便于阅读。我也不想打开“allow_url_fopen”

编辑

这就是我现在所拥有的。

    <?php
      $api_key = 'xxxxxxxxxx';
      $latitude = "40.5122";
      $longitude = "-88.9886";
      $API_ENDPOINT = 'https://api.forecast.io/forecast/';

      $request_url = $API_ENDPOINT .
        $api_key . '/' .
        $latitude . ',' . $longitude;

        $ch = curl_init();

        $headers = array(
            'Content-Type: application/json',
            'Accept: application/json'
        );
        curl_setopt($ch, CURLOPT_URL, $request_url);
        curl_setopt($ch, CURLOPT_HEADER, $headers);

        $result = curl_exec($ch);

        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);


        $content = json_decode($result, true);

        if(empty($content))
            print_r("Empty");
        

    ?>

它告诉我 $content 是空的。如果有的话,我错过了什么。

【问题讨论】:

【参考方案1】:

Dodd 先生是正确的,但 JSONP 的使用表明您正在执行跨站点请求。由于 PHP 通常在服务器端运行,因此您无需担心这一点。您只需要确保您使用的 url 返回 JSON。您可能希望像这样向您的请求添加标头:

$headers = array(
  'Content-Type: application/json',
  'Accept: application/json'
);

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

当您执行请求时,您可以像这样检索响应和 HTTP 状态:

// Get the result
$result = curl_exec($ch);

// Get the status
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

// Close the session
curl_close($ch);

//Parse the JSON
$result_arr = json_decode($result, true);

【讨论】:

我已经更新了我的代码,但是我没有从请求中得到任何东西。我的代码中是否缺少某些内容?我正在尝试从 Forecast.io api 中提取。 您应该尝试从浏览器中使用的 url,看看它是否返回任何内容。您还应该检查上面$httpCode 的HTTP 状态。 我做了 print_r($httpCode),它给了我 0。我把调用 url 放到浏览器 url 中,以确保它是正确的 url(它是)然后我拿了粘贴该 url 代替 $request_url。我仍然得到相同的结果。 您的响应可能超时。您将需要添加超时参数,这里有很好的解释:***.com/questions/2582057/…【参考方案2】:

您可以参考this page 获取有关所有 PHP 的 cURL 函数的文档。另外,我不熟悉 JS 中的 cURL,所以我不确定如何匹配您的选项,但 PHP 的所有 cURL 选项都可以找到 here。

例如,它应该看起来像这样:

// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);

【讨论】:

以上是关于PHP 卷曲标头的主要内容,如果未能解决你的问题,请参考以下文章

处理大卷曲响应 - PHP

php 卷曲 - PHP认证

php 卷曲类PHP

PHP PHP卷曲

php 卷曲php转义查询中的特殊字符

Windows 10 上的 PHP 卷曲,php 5.6.17