PHP message for REST web service

I am completely new to REST web services. I need to send some information to the REST web service using php and use the response to provide the product to users (the answer is the code for the product). My task: 1) HTTP method - message 2) The request body is XML 3) The headers must have an API key ex: some-co-APIkey: 4325hlkjh 4) The answer is xml and needs to be parsed. My main question is: how to set up the headers so that it contains the key, how to set the body and how to get the answer. I don’t know exactly where to start. I am sure that it is quite simple, but since I have never seen this, I am not sure how to approach this. If anyone could show me an example that would be great. Thanks in advance for any help.

I think 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 sound right?

+4
source share
3 answers

For this you should use cURL . You should read the documentation, but the function I wrote here will help you. Change 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 features for parsing it. Check out simplexml .

+7
source

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 the XML parser: http://php.net/manual/en/book.xml.php

+1
source

Just check out the PHP manual on how to execute an HTTP request and read the response. HTTP context parameters and parameters are useful for what you would like to achieve.

If you need a general tutorial on how to make an HTTP POST request, you will find a longer one here: HTTP POST from PHP without cURL . It has a general REST helper , so it may be exactly what you are looking for.

0
source

All Articles