开发者

Very quick example to get me started with fopen / curl request

开发者 https://www.devze.com 2023-03-20 14:46 出处:网络
I am looking to start pulling data from comindwork, but I have never used any web services before so I don\'t really know how to get started.

I am looking to start pulling data from comindwork, but I have never used any web services before so I don't really know how to get started.

Someone has suggested I can pull back data with either fopen or send a curl request, but I don't know which one.

I am using this api:

Projects RETRIEVE Get All Projects

GET /projects.xml
GET|POST /project/list 

Get One Project

GET /projects/{project_id}.xml
GET|POST /开发者_如何学Goproject/show/{project_id}
GET /projects/{project_id} 

Which one will do the job and could you provide a quick example please?

Thank you


Since you need to be able to POST as well as GET, curl would be a good choice (although you could easily use both - fopen for GET and curl for POST).

example POST using curl:

$ch = curl_init();
curl_setopt_array($ch, array(
  CURLOPT_POST => 1,
  CURLOPT_URL => $url,
  CURLOPT_RETURNTRANSFER => TRUE,
  CURLOPT_POSTFIELDS => http_build_query(array(
    'param' => 'value'
  )),
));
if(curl_exec($ch) === FALSE) {
  //handle failure
} else {
  //handle success
}
curl_close($ch);

This is a basic example which would need improvement for a production app. For example, you'd probably need to check response information using curl_getinfo().

example GET using fopen:

$fh = fopen($url, 'r');
$contents = fread($fh);
fclose($fh);

A downside is that if the server returns meaningful headers, you can't read them. Better to use file_get_contents:

$content = file_get_contents($url);
print_r($http_response_header);

You'd then be able to consult the $http_response_header variable to get the returned headers.


I'd have a look at http://www.phpclasses.org/package/3329-PHP-HTTP-client-using-the-PHP-Curl-library.html which is a simple, well commented wrapper around curl that could give you an idea of how it works =)


regarding fopen vs curl: always prefer curl, especially when using it more than 1 time. Obvious reasons like flexibility aside, curl is just about 5 times faster.

0

精彩评论

暂无评论...
验证码 换一张
取 消