PHP接收XML

时间:2012-07-10 01:17:32

标签: php xml curl

我有一个正在侦听POST请求的小PHP脚本。我总是期待xml。 通常我是发送xml请求的人。但今天我在接收方。

我认为这是一个听$ _POST的简单案例,但我想我可能不对 - 我什么也没得到。

这是我的脚本,等待任何xml:

<?php
if(isset($_POST)) {
    mail("me@myemail.com","some title i want", print_r($_POST, true)); 
}else{
    die("uh, what happened?");
}
?>

这是一个我从另一个地方发送的简单xml字符串:

<?php
$xml_data ='
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don\'t forget me this weekend!</body>
</note>
';

function sendXML2Server($URL,$XML){
    $xml_data = trim($XML);
    $ch = curl_init($URL);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);
    curl_close($ch);

    return $output;
}

echo sendXML2Server('https://someurl.com/inboundxml.php',$xml_data)
?>

以下是我在电子邮件中收到的内容:

阵 ( )

我猜我没有正确使用数组,但也许我还缺少其他所有这些内容。我期待收回实际的xml字符串。

2 个答案:

答案 0 :(得分:1)

你只发送数据,这就是为什么PHP无法将这些数据解释为某些键和值。因此,您需要将其作为变量值发送:

curl_setopt($ch, CURLOPT_POSTFIELDS, array('xml_data' => $xml_data));

或作为原始发布数据接收:

<?php
if(isset($HTTP_RAW_POST_DATA)) {
    mail("me@myemail.com","some title i want", print_r($HTTP_RAW_POST_DATA, true)); 
}else{
    die("uh, what happened?");
}
?>

答案 1 :(得分:0)

CURLOPT_POSTFIELDS需要一个数组:

curl_setopt($ch, CURLOPT_POSTFIELDS, array('content'=>$xml_data));

然后检索它:

<?php
if($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['content'])) {
    mail("me@myemail.com","some title i want", print_r($_POST['content'], true)); 
}else{
    die("uh, what happened?");
}
?>