I’m trying to make a JSON call library. It has the following features.
- be able to customize the header
- be able to POST any data to server(including form-encoding (
a=1&b=2&c=3) and JSON data chunk) - parse the response and return as a JSON object
I searched in other questions and found that there are only two answers.
- use
file_get_contents(). This way is pretty simple and easy to use; however, you cannot do anything more than get the content — you cannot add headers, cannot use POST. But it is usually supported by all servers. - use curl. This way seems powerful and you can do nearly everything with it. The disadvantage is that you have to install libcurl and php-curl support on your server, which means you may not use it on servers that have no curl installed.
So, if I want to develop a common library that can be used on most server, is curl a good choice?
Is there any other ways to do this?
In a short word, I’m looking for a PHP version of urllib2 in python – easy to use, powerful, and reliable.
You have two options:
curland HTTP stream context options. Both can accomplish what you have described;curlmight not be installed everywhere, while stream contexts are a core feature and are always available.Actually, you can also implement your library using sockets, which would be more work but will probably allow you greater control if you need to do weirder things with your requests.