X
X
xafes2020-02-27 14:29:06
PHP
xafes, 2020-02-27 14:29:06

Sending a curl post request with data in xml?

There is some XML and a link to a third-party service:

$url = 'https://example.com/';
$xml = '<?xml version="1.0" encoding="UTF-8" ?>
            <Request>
              <Language>ru</Language>
            </Request>';

If submit xml via form:
<form method="post" action="https://example.com/">
  <textarea name="Request"><?php echo $xml; ?></textarea>
  <button>Submit</button>
</form>

Then the server returns the data based on the sent in xml.
I'm trying to do the same with curl:
function sendXmlOverPost($url, $xml) {
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);

  $result = curl_exec($ch);
  curl_close($ch);
  return $result;
}
print_r(sendXmlOverPost($url, $xml));

An error is returned, System error!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
nokimaro, 2020-02-27
@xafes

The problem is that from the form you send data as Request=XXXXXXXXXbecause textarea name="Request", and in curl you send data in the form of raw post data.
The correct submission option, similar to how the data was sent from the form below
Content-Type: text/xml, which FanatPHP clung to, does not play a role, and it can not be sent.

function sendXmlOverPost($url, $xml) {
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['Request' => $xml]));

  $result = curl_exec($ch);
  curl_close($ch);
  return $result;
}
print_r(sendXmlOverPost($url, $xml));

F
FanatPHP, 2020-02-27
@FanatPHP

And why do you write strange words Content-Type: text/xml in curl?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question