PHP curl headers

你说的曾经没有我的故事 提交于 2021-02-07 09:31:36

问题


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

I do it this way for my readability. I also don't want to turn on the "allow_url_fopen"

EDIT

So this is what I have now.

    <?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");
        }

    ?>

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


回答1:


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

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



回答2:


You can refer to this page for documentation on all of PHP's cURL functions. Also, I'm not familiar with cURL in JS, so I'm not sure how to match your options, but all of the cURL options for PHP can be found here.

As an example, It should look something like this:

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


来源:https://stackoverflow.com/questions/27275432/php-curl-headers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!