简体   繁体   中英

Javascript to PHP - Curl request not returning results

I am trying to port over a piece of code that is currently written in Javscript, it has the following line...

    get('http://www.example.com/api.php?key=1234&type=fruit', function(data) {
       console.log(data)
    })

I am trying to write the equivalent in PHP and have this...

$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_URL => 'http://www.example.com/api.php?key=1234&type=fruit',
    CURLOPT_USERAGENT => 'cURL Request'
));

$resp = curl_exec($curl);

curl_close($curl);

print_r($resp);

My PHP version does not return anything, just blank. The Javascript version returns results.

Does my PHP version look correct? I do not have any docs for the API being accessed so am trying to work it out by trial and error

Try using file_get_contents() instead

    $resp = file_get_contents('http://www.example.com/api.php?key=1234&type=fruit');
print_r($resp);

Edit: Maybe The server expect session cookies so add some:

$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_URL => 'http://www.example.com/api.php?key=1234&type=fruit',
    CURLOPT_USERAGENT => 'cURL Request'
));
curl_setopt($ch, CURLOPT_COOKIEFILE, '/tmp/cookies.txt'); // set cookie file to given file
curl_setopt($ch, CURLOPT_COOKIEJAR, '/tmp/cookies.txt'); // set same file as cookie jar
$resp = curl_exec($curl);
curl_close($curl);
print_r($resp);

you need to check for errors , here's a simple implementation of get function :

<?php

function request(string $url,string $method = 'GET',array $data = [],?Closure $success=null,?Closure $fail=null): void
{
     $ch = curl_init();
     curl_setopt_array($ch, [
         CURLOPT_RETURNTRANSFER => 1,
         CURLOPT_URL => $url,
         CURLOPT_USERAGENT => 'PHP Curl',
         CURLOPT_POSTFIELDS => $data,
         CURLOPT_CUSTOMREQUEST => $method,
    ]);
    if($result = curl_exec($ch)) 
    {
         if($success !== null) 
            $success($result);
    } else {
        if($fail !== null)
            $fail($ch);
    }
    curl_close($ch);
}

function get($url,$success,$fail) 
{
    request($url,'GET',[],$success,$fail);
}

get('http://www.example.com/api.php?key=1234&type=fruit',
function($result) {
   print $result;
},
function($ch) {
   print 'Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch)
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM