Reputation: 43
I'm totally new to REST web services. I have a need to post some information to a REST web service using php and use the response to give users a product(the response is the code for the product). My task : 1) HTTP method is post 2) Request body is XML 3) Headers need to have an API key ex: some-co-APIkey: 4325hlkjh 4) Response is xml and will need to be parsed. My main question is how to set the headers so that it contains the key, how to set the body, and how to get the response. I am unsure exactly where to start. I'm sure it's quite simple but since I've never seen it I'm not sure how to approach this. If someone could show me an example that'd be great. Thanks in advance for any and all help.
I'm thinking something like this;
$url = 'webservice.somesite.com';
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<codes sku="5555-55" />';
$apiKey = '12345';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
## For xml, change the content-type.
curl_setopt ($ch, CURLOPT_HTTPHEADER, $apiKey);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // ask for results to be returned
if(CurlHelper::checkHttpsURL($url)) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
}
// Send to remote and return data to caller.
$result = curl_exec($ch);
curl_close($ch);
Does that seem about right?
Upvotes: 4
Views: 12798
Reputation: 198217
Just check the PHP manual how to perform a HTTP request and read the response. The HTTP context options and parameters are useful for what you would like to achieve.
If you need a general tutorial on how make a HTTP POST request, you find a more lengthy one here: HTTP POST from PHP, without cURL. It has a generic REST helper as well, so it might be exactly what you're looking for.
Upvotes: 0
Reputation: 2021
If you can install/have access to cURL it will do what you want:
cURL Manual: http://php.net/manual/en/book.curl.php
Examples: http://php.net/manual/en/curl.examples.php
And an XML parser: http://php.net/manual/en/book.xml.php
Upvotes: 1
Reputation: 26789
You should use cURL for this. You should read the documentation, but here is a function I wrote that will help you out. Modify it for your purposes
function curl_request($url, $postdata = false) //single custom cURL request.
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
if ($postdata)
{
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
}
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
As for XML, php has some great functions for parsing it. Check out simplexml.
Upvotes: 8