[英]How to POST an XML file using cURL on php?
我在計算機上使用本地服務器,並且嘗試制作2個php腳本來發送和接收xml文件。
要發送xml文件,我使用以下代碼:
<?php
/*
* XML Sender/Client.
*/
// Get our XML. You can declare it here or even load a file.
$file = 'http://localhost/iPM/books.xml';
if(!$xml_builder = simplexml_load_file($file))
exit('Failed to open '.$file);
// We send XML via CURL using POST with a http header of text/xml.
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://localhost/iPM/receiver.php");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_builder);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_REFERER, 'http://localhost/iPM/receiver.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$ch_result = curl_exec($ch);
curl_close($ch);
// Print CURL result.
echo $ch_result;
?>
要接收xml文件,請使用以下代碼:
<?php
/*
* XML Server.
*/
// We use php://input to get the raw $_POST results.
$xml_post = file_get_contents('php://input');
// If we receive data, save it.
if ($xml_post) {
$xml_file = 'received_xml_' . date('Y_m_d-H-i-s') . '.xml';
$fh = fopen($xml_file, 'w') or die();
fwrite($fh, $xml_post);
fclose($fh);
// Return, as we don't want to cause a loop by processing the code below.
return;
}
?>
當我運行發布腳本時,出現此錯誤:
Notice: Array to string conversion in C:\xampp\htdocs\iPM\main.php on line 17
這是指行:
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_builder);
我不知道到底是什么。 我收到的xml文件已創建,但是當我打開它時,得到以下消息:
XML Parsing Error: syntax error
Location: file:///C:/xampp/htdocs/iPM/received_xml_2013_01_14-01-06-09.xml
Line Number 1, Column 1:
我試圖注釋此特定行,因為我認為問題出在那兒,但是當我運行我的發布腳本時,出現此錯誤:
Request entity too large!
The POST method does not allow the data transmitted, or the data volume exceeds the capacity limit.
If you think this is a server error, please contact the webmaster.
Error 413
但是xml文件只有5kbs,所以這不是問題。
有誰知道我在這里應該做什么? 我想要做的就是制作一個發送xml文件的腳本和一個接收它並將其另存為xml的腳本。
curl_setopt($ch, CURLOPT_POSTFIELDS, $foo)
設置請求的正文,即要發布的數據。 它期望$foo
是一組作為數組提供的鍵/值對:
$foo = array(
'foo' => 'some value',
'bar' => 2
);
或作為百分比編碼的字符串:
$foo = 'foo=some%20value&bar=2'
相反,您提供的是$xml_builder
變量,它是由simplexml_load_file($file)
返回的SimpleXMLElement
對象。
嘗試這個:
$postfields = array(
'xml' => $your_xml_as_string; // get it with file_get_contents() for example
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
然后在接收端:
$received_xml = $_POST['xml'];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.