I'm working with an external开发者_Go百科 API webservice that returns a json output true or false. I visit a URL like
http://site.com/api/valid
and it gives me something like this, which looks like json
"true"
Right now I'm visiting the url manually, but I want to now do it programmatically from within my zend project. What should I use to get the result correctly
there are a lot of ways. The simplest is to use file_get_contents()
.
$result = file_get_contents("http://site.com/api/valid");
// if result is truly json
// data will be
// array( 0 => true)
$data = json_decode($result);
If it is a popular webservice . there might be a library written for it already. This is preferred since it will handle error conditions and corner cases. Google around for it first.
Sounds like you need a method that can grab the endpoint. Well, there's many ways but since you are already using Zend, you might as well read up on http://framework.zend.com/manual/1.11/en/zend.http.client.adapters.html
Here's a static method:
static function curl($url, $method, $params = array()){
$client = new Zend_Http_Client($url);
if($method == "POST"){
$client->setParameterPOST($params);
}else{
$client->setParameterGet($params);
}
$response = $client->request($method);
return $response->getBody();
}
Or use php's native method $response = file_get_contents($url);
Make sure to json_decode() your responses.
精彩评论