1

我在我的计算机上使用本地服务器,我正在尝试制作 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;
  }
?>

当我运行 post 脚本时,出现此错误:

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。

4

1 回答 1

6

curl_setopt($ch, CURLOPT_POSTFIELDS, $foo)设置您的请求正文,即要发布的数据。它期望$foo是一组键值对作为数组提供:

$foo = array(
    'foo' => 'some value',
    'bar' => 2
);

或作为百分比编码的字符串:

$foo = 'foo=some%20value&bar=2'

相反,您提供$xml_builder的变量是SimpleXMLElementsimplexml_load_file($file).

试试这个:

$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'];
于 2013-01-14T01:09:28.543 回答