PHP curl标头 [英] PHP curl headers

查看:77
本文介绍了PHP curl标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太擅长使用PHP和cURL,通常我只是使用javascript或C#进行调用,但是我使用的是wordpress,所以C#不太可能,而且在调用URL中有一个apikey,所以我想知道我是否可以对此有所帮助.在javascript中,呼叫会是.

I am not very good using PHP and cURL, normally I just make a call with either javascript or C# however I am working with wordpress so C# is not possibly, and I have an apikey with in the call url, so I was wondering if I could have some help with this. In javascript, the call would be.

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

我这样做是为了提高可读性.我也不想打开"allow_url_fopen"

I do it this way for my readability. I also don't want to turn on the "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为空.我有什么想念的?

It is telling me that $content is empty. What am I missing if anything.

推荐答案

Dodd先生是正确的,但是使用JSONP表示您正在执行跨站点请求.由于PHP通常在服务器端运行,因此您无需担心.您只需要确保您使用的网址返回JSON即可.您可能需要像这样将标头添加到您的请求中:

Mister Dodd is correct, but the use of JSONP suggests that you were doing a cross-site request. Since PHP generally runs on the server side you won't need to worry about that. You will just need to ensure that the url you use returns JSON. You may want to add headers to your request like this:

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

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

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

When you execute the request, you can retrieve the response and the HTTP status like this:

// 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);

这篇关于PHP curl标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆