Home Calling an API in PHP without cURL
Reply: 2

Calling an API in PHP without cURL

Pikapops Published in 2018-02-14 10:22:25Z

After writing the cURL script to to get what I wanted - I found out that the web server doesn't support cURL and only supports pure PHP. How would I go about doing this in pure PHP?

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://xx.xxxx.xxx/xxx/blog/micro");
curl_setopt($ch, CURLOPT_HTTPGET, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$headers = [
    'Header1: Header1Input',
    'Header1: Header2Input',

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$server_output = curl_exec ($ch);

curl_close ($ch);
 $json = $server_output;
 $data = json_decode($json);

print  $data[1]->Headline;?>

Is what has managed to work for me.

I have tried this approach for pure PHP:


// Create a stream
$opts = [
    "http" => [
            "method" => "GET",
            "header" => "Header1: Header1Input" .
            "Header2: Header2Input"

$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
$file = file_get_contents('https://xx.xxxx.xxx/xxx/blog/micro', false, $context);

$file = json_decode($file);

print  $file[1]->Headline;?>

However I get this error:

failed to open stream: HTTP request failed!


WasteD Reply to 2018-02-14 10:35:15Z

I can see the problem in the header after each line you have to add \r\n (CR LF).

This is defined here.

HTTP/1.1 defines the sequence CR LF as the end-of-line marker for all protocol elements except the entity-body.

luigif Reply to 2018-02-14 10:42:44Z

Using a cURL emulator class, such as https://github.com/vavrecan/curl-emulator, you also get support for CURLOPT options.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.299689 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO