-1

I am trying to send XML file via XmlHttpRequest but unfortunately nothing is sent, when I print $_POST
it gives me an empty array. I tried two ways to create XML

  1. createDocument
  2. XMLstring then parseFromString to xml.

but to no avail.

I think the reason is the header:

xmlhttp.setRequestHeader('Content-Type', 'text/xml');

because when I replace it with this header

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

it works but it sends string not xml file I know that I can send xml string to my php then parse it to xml file but I don't want this way, I need to send xml file directly

even if i changed header to text/xml and used in php

$rawData = file_get_contents("php://input");
echo gettype ($rawData);

it returns string so I have to use simplexml_load_string to convert it to object this is my js code:

var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","http://localhost/dashboard/webservice/SOAP/soapServer/ex.php");
var xmlDoc;
xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    xmlDoc = xmlhttp.response;
    console.log(xmlDoc);          
    }
};
//xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader('Content-Type', 'text/xml');

//way1
var xmlString = "<?xml version='1.0'?><root><query><author>John Steinbeck</author></query></root>";
var parser = new DOMParser();
  var xmlDoc = parser.parseFromString(xmlString, "text/xml");

//way2
var doc = document.implementation.createDocument("", "", null);
var peopleElem = doc.createElement("people");
var personElem1 = doc.createElement("person");
personElem1.setAttribute("first-name", "eric");
personElem1.setAttribute("middle-initial", "h");
personElem1.setAttribute("last-name", "jung");
  
xmlhttp.send(xmlDoc);

php code ,so simple:

?php
header("Access-Control-Allow-Origin: http://localhost:3000");
var_dump($_POST);
?>
HUS.97
  • 7
  • 1
  • 5
  • Does this answer your question? [PHP "php://input" vs $\_POST](https://stackoverflow.com/questions/8893574/php-php-input-vs-post) – gre_gor May 25 '20 at 23:52
  • thnx for helping... I am afraid not, I can use text/xml header with file_get_contents but it still the same problem it returns string when i print gettype() – HUS.97 May 26 '20 at 19:11

1 Answers1

1

I can use text/xml header with file_get_contents

That is the correct approach.

but it still the same problem it returns string when i print gettype() –

PHP will automatically parse a request with a application/x-www-form-urlencoded body or a multipart/form-data body and populate $_POST with the data.

Those are the only content-types it has any automatic handling for. It has no features for automatically parsing an XML body. You have to do it explicitly (by reading the body from STDIN and then passing the resulting string through an XML library).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335