Beyerz
Beyerz

Reputation: 828

posting xml to a rest api with php

I really hope someone can help me along with this one...

I need to do an xml POST to RESTful API using php, but I have absolutely no clue where to start.

I can build the xml, but how do I post the it? I cant use cURL library.

Upvotes: 1

Views: 5364

Answers (2)

ms1205
ms1205

Reputation: 11

I was stuck with the same problem a couple of days ago and finaly someone came up with this solution, but do not use $this->_request to get the post request as it doesn't work with xml, not at least in my case.

$service_url1 = 'http://localhost/restTest/respond/';
$curl1 = curl_init($service_url1);
curl_setopt($curl1, CURLOPT_RETURNTRANSFER, true);
$arr=array("key"=>$xml);
curl_setopt($curl1, CURLOPT_POST, 1);
curl_setopt($curl1, CURLOPT_POSTFIELDS,$arr);
echo $curl1_response = curl_exec($curl1);

curl_close($curl1);

Upvotes: 1

alganet
alganet

Reputation: 2547

You can use file_get_contents(). allow_url_fopen must be set on php.ini.

$context = stream_context_create(array('http'=>array(
    'method' => 'POST'
    'content' => $myXMLBody
)));
$returnData = file_get_contents('http://example.com/restfulapi', false, $context);

This is possible because PHP abstracts stream manipulation with his own wrappers. Setting a context to stream manipulation functions (like file_get_contents()) allows you to configure how PHP handles it.

There are more parameters than just method and content. You can set request headers, proxies, handle timeouts and everything. Please refer to the manual.

Upvotes: 2

Related Questions