I-M-JM
I-M-JM

Reputation: 15950

better option to fetch data using api call, what to use: fopen, file_get_contents, and cURL

I am fetching data using API call.

I want to know which would be better option

fopen, file_get_contents, OR cURL

Kindly help.

EDIT I have to make API call to remote system

Upvotes: 2

Views: 1056

Answers (4)

Wiseguy
Wiseguy

Reputation: 20883

You may be able to use file_get_contents(). It depends if your configuration has the allow_url_fopen setting turned on. If not, you won't be able to use file_get_contents() nor fopen(), as they both depend on this setting. In that case, you'd need cURL.

You won't need to use fopen(). Either you can use file_get_contents() instead, or you'll have to use cURL.

Upvotes: 0

Demian Brecht
Demian Brecht

Reputation: 21368

Depends on how much you need to tailor your request..

  • fopen returns a resource which you must use to read the response manually
  • file_get_contents does all of the reading for you (that you have to do manually using fopen and returns the resulting string
  • curl is tailored specifically for network transactions (and according to this post, is quite a bit faster than file_get_contents and provides an API to set header values

All three allow you to tailor your request headers, but doing so with fopen and file_get_contents requires you to use a context callback to set the values with stream_context_create().

Generally, file_get_contents seems to be commonplace when you need to do a simple GET on static data. curl seems to be standard when doing anything else.

Upvotes: 4

JohnP
JohnP

Reputation: 50019

This depends on your setup.

fopen and file_get_contents can only be used for getting data over a URL if allow_url_fopen is enabled. So you can't use this if your host has disabled this.

If that's the case, you can still use cURL. cURL also allows you to have a lot more flexibility when working with remote URI calls.

Upvotes: 1

fingerman
fingerman

Reputation: 2470

This depends on your usage, since you say api call, I'll guess this is not local...

If you're calling requests lots of times, use cull, has it has very good preformence.

If you are calling it little times, and Don't know how to use curl, then file_get_contents should suffice.

https://stackoverflow.com/questions/555523/file-get-contents-vs-curl-what-has-better-performance

Upvotes: 1

Related Questions