1

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.

Beyerz
  • 787
  • 2
  • 9
  • 20
  • Why can't you use cURL? [This question](http://stackoverflow.com/questions/2478077/php4-http-post-without-curl) may help. – Bojangles Apr 22 '12 at 13:14
  • I need this script to run on a number of servers, some of which may not have the Library, so I cant rely on it. – Beyerz Apr 22 '12 at 13:24
  • @JamWaffles ok, turns out I can use cURL. I have put something together, but now I am stuck separating the http returned headers and the xml return. – Beyerz Apr 24 '12 at 07:21
  • `code`$ch = curl_init($this->ApiUrl . $method ."/"); curl_setopt($ch, CURLOPT_HEADER, 1);// header will be part of output curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml')); curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml_data"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); – Beyerz Apr 24 '12 at 07:22
  • how would I separate the two? I need this to check if I got errors. – Beyerz Apr 24 '12 at 07:22

2 Answers2

2

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.

alganet
  • 2,527
  • 13
  • 24
  • Thx you for this solution. This have help me to call a REST API which using XML without Guzzle (old project). – nboulfroy Jan 21 '20 at 11:29
1

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);
Toon Krijthe
  • 52,876
  • 38
  • 145
  • 202
ms1205
  • 11
  • 1