Post xml rest php

Receiving XML via POST in PHP.

In this tutorial, I will show you how to receive an XML string via raw post data using PHP. This can be accomplished by using the php://input IO stream.

Let’s take a look at the following PHP example:

//Make sure that this is a POST request. if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0) < //If it isn't, send back a 405 Method Not Allowed header. header($_SERVER["SERVER_PROTOCOL"]." 405 Method Not Allowed", true, 405); exit; >//Get the raw POST data from PHP's input stream. //This raw data should contain XML. $postData = trim(file_get_contents('php://input')); //Use internal errors for better error handling. libxml_use_internal_errors(true); //Parse the POST data as XML. $xml = simplexml_load_string($postData); //If the XML could not be parsed properly. if($xml === false) < //Send a 400 Bad Request error. header($_SERVER["SERVER_PROTOCOL"]." 400 Bad Request", true, 400); //Print out details about the error and kill the script. foreach(libxml_get_errors() as $xmlError) < echo $xmlError->message . "\n"; > exit; > //var_dump the structure, which will be a SimpleXMLElement object. var_dump($xml);
  • We started off by validating the request method. If the request is not a POST request, our PHP script will send back a “405 Method Not Allowed” header to the client and then kill the script. This means that our script can not be accessed via GET, DELETE or HEAD, etc.
  • Using the php://input IO stream, we retrieved the raw post data. This stream allows us to read raw data from the request body.
  • We disabled the standard libxml errors by using the libxml_use_internal_errors function. As a result, we can control how XML validation errors are displayed. If you fail to do this, XML errors will be immediately outputted.
  • Using the simplexml_load_string function, we converted our XML string into a SimpleXMLElement object.
  • If we were unable to convert the string into an object, then it means that there were issues with the XML that we received. The function simplexml_load_string will return a boolean FALSE value if the string could not be converted. We handle such errors by sending a “400 Bad Request” to the client and by printing out the error messages.
  • Finally, we do a var_dump on the SimpleXMLElement object.
Читайте также:  Python dasturlash tili kutubxonasi

Hopefully, you found this guide helpful!

Источник

PHP: Send XML via POST.

This is a guide on how to send XML via a POST request using PHP. In this tutorial, I will be using the inbuilt cURL functions to send the request.

Let’s jump right in and take a look at the following code:

//The XML string that you want to send. $xml = '  2019-20-02T10:45:00 Meeting Team meeting in Boardroom 2A. '; //The URL that you want to send your XML to. $url = 'http://localhost/xml'; //Initiate cURL $curl = curl_init($url); //Set the Content-Type to text/xml. curl_setopt ($curl, CURLOPT_HTTPHEADER, array("Content-Type: text/xml")); //Set CURLOPT_POST to true to send a POST request. curl_setopt($curl, CURLOPT_POST, true); //Attach the XML string to the body of our request. curl_setopt($curl, CURLOPT_POSTFIELDS, $xml); //Tell cURL that we want the response to be returned as //a string instead of being dumped to the output. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); //Execute the POST request and send our XML. $result = curl_exec($curl); //Do some basic error checking. if(curl_errno($curl)) < throw new Exception(curl_error($curl)); >//Close the cURL handle. curl_close($curl); //Print out the response output. echo $result;
  1. We assigned our XML string to a PHP variable.
  2. We initiated cURL and specified the URL that we want to send our XML data to.
  3. Using the CURLOPT_HTTPHEADER option, we set the Content-Type header to text/xml. This may or may not be required depending on the service that you are sending your POST request to.
  4. In order to tell cURL that we want to send a POST request, we set the CURLOPT_POST option to TRUE. By default, cURL will send a GET request.
  5. We assigned our XML data to the body of the request.
  6. We told cURL to return the response output as a variable by setting the CURLOPT_RETURNTRANSFER option to TRUE.
  7. Finally, we executed the request and printed out the response. We also added in some basic error checking, just in case the request fails.
Читайте также:  Css has not work

Send XML without cURL.

If you do not have access to the cURL functions, then you can check out my guide on sending a POST request without cURL.

Note that you may need to modify the function and change the header value on LINE 17. You may also need to remove the http_build_query function on LINE 11. This will all depend on the service you are sending your XML to.

Send XML file data via cURL.

If your XML content is located in a file, then you can read the contents of that file using the file_get_contents function:

//Read the XML file in as a string. $xml = file_get_contents('file.xml');

In the example above, the file_get_contents function reads in XML data from a file called file.xml and assigns it to the variable $xml. This code would replace the XML assignment on LINE 2 of the original example above.

Hopefully, you found this post to be helpful!

Related article: Receive XML via POST.

Источник

How to Consume XML Rest API Using PHP

This lumen tutorial help to create a rest wrapper using lumen to consume XML type Rest API. I have already shared a tutorial to consume JSON type rest API but this example will use XML type rest service that sends XML as a response.

XML is another popular data format to read input and send response output using web-service. The XML format can be used for rest or SOAP type web service.

I am using the lumen framework to consume XML type restful web service. If you are not familiar with lumen or laravel, please read the below tutorials:

You can also use the same mechanism for CURL or other rest PHP frameworks.

We will create a client wrapper for the rest server. We will use webservice host url and set header information.

$client = new Client([ // Base URI is used with relative requests 'base_uri' => 'restapi url', //https://hostname/api/ // You can set any number of default request options. 'timeout' => 2.0, 'headers' => ['Content-Type' => 'application/json', "Accept" => "application/json"], //ssl false 'verify' => false ]);

We will pass XML rest endpoints to the client get method and get rest response body content,

$response = $client->get("computer/api/xml")->getBody();

Now we will parse XML data and convert it into JSON data using json_encode. For data processing, I have converted JSON into PHP array using json_decode method.

$xml = simplexml_load_string($response); $json = json_encode($xml); $array = json_decode($json,TRUE);

Источник

Читайте также:  Как изучить синтаксис javascript

Как сделать post запрос xml?

Следует выполнить POST запрос на добавление нового подписчика из xml и вывести результат (ответное xml).
Как это реализовать? curl?
Прочитал темы по сабжу, но, видимо, не все понял. можно на моем примере пояснить?

POST не может быть безымянным, должно быть поле в котором будут переданы данные, в вашем случае это xml. Не совсем понятна суть, вам надо решить вопрос с какой стороны сервера или клиента апи?

т.е. у меня на сайте стоит форма. в ней поля — Имя, Email и checkbox получать рассылку или нет
если стоит галочка получать рассылку, то в mysite.com/api/
нужно послать xml запрос методом post с текстом (указанным выше)

$ch = curl_init(); $data = array('request' => $xml); curl_setopt($ch, CURLOPT_URL, "http://mysite.com/api/"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $response=curl_exec($ch); curl_close($ch); print_r($response); 
$data = array('request' => $xml,'Content-Type: text/xml; charset=utf-8'); 
$ch = curl_init(); $data = array('Content-Type: text/xml; charset=utf-8'); curl_setopt($ch, CURLOPT_URL, "http://mysite.com/api/api?"+$xml); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $response=curl_exec($ch); curl_close($ch); print_r($response); 
 xxxx AddAndUpdate false 1 aa@aa.aa name  '; $ch = curl_init(); $data = array('Content-Type: text/xml; charset=utf-8'); curl_setopt($ch, CURLOPT_URL, "https://mysite.com/api?"+$xml); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $response=curl_exec($ch); curl_close($ch); print_r($response); ?>

однако, есть пример на c# (asp), реализующий то же самое. Он рабочий.

WebRequest request = WebRequest.Create("https://mysite.com/api"); request.Method = "POST"; string postData = @" xxxx AddAndUpdate false 1 aa@aa.aa name  "; byte[] byteArray = Encoding.UTF8.GetBytes(postData); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = byteArray.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); try < WebResponse response = request.GetResponse(); >catch (WebException ex) < // using (Stream data = ex.Response.GetResponseStream()) // < // string text = new StreamReader(data).ReadToEnd(); // Response.Write("

" + text); // > >

и почему-то в мануале написано про контент тайп text/xml, а в примере application/x-www-form-urlencoded

MrBlack, curl_setopt($ch, CURLOPT_POSTFIELDS, $data); замените на curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); , и добавьте curl_setopt($ch, CURLOPT_HTTPHEADER, array($xml);

Источник

Оцените статью