PHP отправлять и получать XML
Я работал над API для получения XML-файла, который, в свою очередь, будет прочитан в нашей базе данных. Разбор и все работали с локальными файлами XML. Теперь последний шаг состоял в том, чтобы проверить, работает ли получение XML, и есть ли там, где я наткнулся на контрольно-пропускной пункт. До сих пор пробовал много разных вещей, но не могу заставить его работать. Мы бы предпочли работать с методом REST, но если он действительно не сработает, мы готовы его переключить. Видел много вопросов для отправки или получения файла XML, но никогда не в сочетании. Надеюсь, я смогу получить исчерпывающий ответ на этот вопрос и не пропустить дублирующий вопрос.
TL; DR: отправка и получение XML-файлов через PHP, не знаю, где я делаю ошибку
Отправляющая и получающая части находятся в разных сценариях.
//Sending XML script. $ch = curl_init($url); curl_setopt($ch, CURLOPT_MUTE, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml', 'Content-length: '.strlen($xmlSend))); curl_setopt($ch, CURLOPT_POSTFIELDS, array("recXML" => $xmlSend)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($ch); //Receiving XML script if(isset($_REQUEST['recXML'])) < $xmlTest = $_REQUEST['recXML']; >else < echo "NO REQUEST XML FOUND "; >if(isset($HTTP_RAW_POST_DATA)) < $xmlTest = $HTTP_RAW_POST_DATA; >else < echo " NO RAW DATA "; >if(isset($_POST['recXML']))< $xmlTest = $_POST['recXML']; >else < echo " NO XML RECEIVED "; >if(!isset($xmlTest))
Это не полная логика, но я думаю, что эти части имеют значение, если вы хотите больше кода, просто спросите.
после некоторых изменений и перезагрузки моего компьютера, он наконец заработал. Так что не совсем уверен, какое изменение решило проблему, но опубликует код ниже на случай, если кто-нибудь когда-нибудь найдет для него применение.
//Sending script: $ch = curl_init($url); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml', 'Content-length: '.strlen($xml))); curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($ch); //receiving script $xmlTest = file_get_contents("php://input"); echo $xmlTest; $res = simplexml_load_string($xmlTest); if($res === false)< echo "Failed loading XML: "; foreach(libxml_get_errors() as $error)< echo "
", $error->message; > return; > else < //print_r($res); >
Решение
Вы должны отправить Content-Type как application/xml
так твой код станет
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml', 'Content-length: '.strlen($xmlSend))); curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlSend);
и на приемной стороне вы можете использовать
$xml = file_get_contents("php://input");
Для вашего текущего кода вы можете установить тип контента как application/x-www-form-urlencoded вы можете использовать $_POST[‘recXML’]
Другие решения
DOMDocument::saveXML
Creates an XML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.
Parameters
Use this parameter to output only a specific node without XML declaration rather than the entire document.
Additional Options. Currently only LIBXML_NOEMPTYTAG is supported.
Return Values
Returns the XML, or false if an error occurred.
Errors/Exceptions
DOM_WRONG_DOCUMENT_ERR
Raised if node is from another document.
Examples
Example #1 Saving a DOM tree into a string
$doc = new DOMDocument ( ‘1.0’ );
// we want a nice output
$doc -> formatOutput = true ;
$root = $doc -> createElement ( ‘book’ );
$root = $doc -> appendChild ( $root );
$title = $doc -> createElement ( ‘title’ );
$title = $root -> appendChild ( $title );
$text = $doc -> createTextNode ( ‘This is the title’ );
$text = $title -> appendChild ( $text );
echo «Saving all the document:\n» ;
echo $doc -> saveXML () . «\n» ;
echo «Saving only the title part:\n» ;
echo $doc -> saveXML ( $title );
The above example will output:
Saving all the document:Saving only the title part:
See Also
- DOMDocument::save() — Dumps the internal XML tree back into a file
- DOMDocument::load() — Load XML from a file
- DOMDocument::loadXML() — Load XML from a string
User Contributed Notes 17 notes
How to display two tags when the node content is empty.
$dom = new \ DOMDocument ( ‘1.0’ );
$document = $dom -> createElement ( ‘document’ );
$document = $dom -> appendChild ( $document );
$head = $dom -> createElement ( ‘title’ , ‘this is title’ );
$content = $dom -> createElement ( ‘content’ , » );
$document -> appendChild ( $head );
$document -> appendChild ( $content );
echo $dom -> saveXML ();
?>
In XML, they are considered exactly the same thing, and any parser should recognize both forms.However, you can write it this way if you still need it
echo $dom -> saveXML ( $dom -> documentElement , LIBXML_NOEMPTYTAG );
?>
Example 1:
It took some searching to figure this one out. I didn’t see much in the way of explaining this glitch in the manual thus far. (For PHP5 I believe)
formatOutput = true; appears to fail when the origin of the DOM came from a file via load(). EX:
$dom = new DOMDocument ();
$dom -> load ( «test.xml» );
$dom -> formatOutput = true ;
$new_tag = $dom -> createElement ( ‘testNode’ );
$new_tag -> appendChild (
$dom -> createElement ( ‘test’ , ‘this is a test’ ));
$dom -> documentElement -> appendChild ( $new_tag );
printf ( «
%s
» , htmlentities ( $dom -> saveXML ()));
?>
Will not indent the output and will display the modified nodes all in one long line. Makes for editing a config.xml a bit difficult when saving to a file.
By adding the preserveWhiteSpace = false; BEFORE the load() the formatOutput works as expected. EX:
$dom = new DOMDocument ();
$dom -> preserveWhiteSpace = false ;
$dom -> load ( «test.xml» );
$dom -> formatOutput = true ;
$new_tag = $dom -> createElement ( ‘testNode’ );
$new_tag -> appendChild (
$dom -> createElement ( ‘test’ , ‘this is a test’ ));
$dom -> documentElement -> appendChild ( $new_tag );
printf ( «
%s
» , htmlentities ( $dom -> saveXML ()));
?>
CAUTION: If your loaded xml file (test.xml) has an empty root node that is not shortened or has no children this will NOT work.
if you are storing multi-byte characters in XML, then saving the XML using saveXML() will create problems. It will spit out the characters converted in encoded format.
$str = domdoc -> saveXML (); // gives «&x#1245;» some encoded data
?>
Instead do the following
$str = domdoc -> saveXML ( domdoc -> documentElement ); // gives «保存しました» correct multi-byte data
?>
When you save whole document:
DOMDocument->saveXML() produces string in encoding defined in property DOMDocument->encoding.
When you save only one node:
DOMDocument->saveXML(DOMNode) produces always string in UTF-8.
Quick tip to minimize memory when generating documents with DOM.
Rather than using
$xmlStr = DOMDocument->saveXML();
echo $xmlStr;
to dump a large DOM to the output buffer, use a PHP output stream, as in
A lot of memory will be saved when generating large DOMs.
The simpliest (and probably the fastest) way to strip an XML declaration () out of output document, is to output child nodes of DOMDocument separately:
?xml>
$document = new DOMDocument ();
$document -> load ( ‘/some/file.xml’ );
// this will also output doctype and comments at top level
foreach( $document -> childNodes as $node )
$result .= $document -> saveXML ( $node ). «\n» ;
?>
This might be userful when dealing with browser compatibility issues, for example, well known problem with valid XHTML in IE6.
Comment to `devin at SPAMISBAD dot tritarget dot com»s post:
Thanks for pointing out the pitfalls of `formatOutput’ vs. `load*()’. This has certainly saved me from some possible surprises.
I think the seemingly strange behaviour can be explained. Warning: The following stuff is mostly based on deductions and experiments. Much less on studying the sources and specs (I’m not sure some of these would provide answer anyway, at least not easily).
As you point out, `preserveWhiteSpace’ must be set before loading the DOM from the source string (I’m working with `loadXML()’ but I believe the situation should be the same with `load()’ you used). This looks logical, as this property seems to control the parsing and DOM creation process during which text nodes containing the whitespace are either included or dropped. This can be proven by dumping the DOM structure and comparing the results based on the value of `preserveWhiteSpace’. With `preserveWhiteSpace’ set to `FALSE’, no text nodes containing whitespace will be present in the returned DOM. When this property is `TRUE’, these nodes will be present.
Note: When speaking about the whitespace in the previous paragraph, we’re most certainly speaking about so called `whitespace in element content’ or `element content whitespace’, if I’m not mistaken. See also my comment in the notes of `DOMText->isWhitespaceInElementContent()’ method.
As for the mysterious effect on the output of `saveXLM()’, I think the explanation lies in the presence or absence of the above mentioned whitespace text nodes. This was also proven by experiments: After adding such a node into a DOM which contained none (the DOM was created using `loadXML()’ with `preserveWhiteSpace’ set to `FALSE’), the output formatting got affected in a such a way, the formatting got lost for the rest of the document after the added node. I think the presence of whitespace text nodes forces such rendering, that the content of these nodes is used to separate adjoining nodes thus disabling default formatting. Only when there are no such text nodes present, the ouput formatting takes effect (provided the `formatOutput’ is set to `TRUE’, of course).
Well, the thing I don’t really understand is how you did get an output of a signle line with `formatOutput’ set to `TRUE’. This has happened to me when no whitespace text nodes were present (ie. when loading the XML with `preserveWhiteSpace’ set to `FALSE’) *and* with `formatOutput’ set to *`FALSE’* (with the opposite value of `formatOutput’, the formatting should do it’s work and you should not end up with just one line). But I haven’t seen your source. Perhaps you had whitespace nodes containing no new-lines in your DOM?
As for the CAUTION about root element, I didn’t see any problems with empty root element neither in shortened nor full form. What did you have in mind, when you said it `WORKS’ or `DOES NOT WORK’?