通过curl将PHP发送的XML解析为另一个PHP脚本

时间:2014-01-05 13:31:32

标签: php xml curl

谢谢大家,我已经解决了这个问题,并在下面就这个问题写了我自己的答案。谢谢大家的尝试


我有一个简单的(我希望)问题,因为我是一个完整的新手。

所以我有2个php文件output.phpinput.php

output.php正在通过cURL向input.php发送XML,如下所示:

$myXML  = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
$myXML .= '<request>
               <message>Hello StackOverflow</message>
               <params>
                   <name>John</name>
                   <lname>Smith</lname>
               </params>
           </request>';

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://localhost/curltest/input.php');
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $myXML);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
    array(
        'Content-type: text/xml; charset=UTF-8',
        'Expect: '
    )
);

$curl_response= curl_exec($curl);

目前input.php的内容如下所示

<?php
// Yes, this is all

问题我根本不知道如何在input.php中获取和解析XML数据,并从该XML中获取数据以便在input.php中使用脚本。

$_POSTinput.php中的空数组,但XML肯定会达到input.php,因为readfile('php://input');内的input.php会显示收到的XML。

我已经阅读过关于DOMElement但我在某些情况下如何使用它有点不清楚。我也在谷歌和SO上搜索过,但没有成功找到我需要的东西。

如果有人能告诉我这是怎么做的那就太棒了。或者至少指出我正确的方向,我在这里不知所措。

P.S。 我无法更改output.php 中的任何内容。 如果需要,我很乐意提供任何其他信息。

3 个答案:

答案 0 :(得分:1)

Simple XML是一个非常好的XML解析/读/写库。

http://www.php.net/manual/en/book.simplexml.php

<强> PHP:

$file = new SimpleXMLElement($file);
echo "<b>Testing:</b> {$file->testing} <br/>";

<强> XML:

<document>
    <testing>Value</testing>
</document>

您可以从文件和变量中使用Simple XML。

您可以在此处找到有关它的更多信息:http://www.php.net/manual/en/simplexmlelement.construct.php

答案 1 :(得分:1)

你需要改变

curl_setopt($ch, CURLOPT_POSTFIELDS, $myXML);

curl_setopt($ch, CURLOPT_POSTFIELDS,  http_build_query(array('xml' => $myXML)));

然后在input.php文件中,您可以使用$_POST['xml'];

获取数据

所以在你的input.php然后做

$xmldata = new SimpleXMLElement($_POST['xml']);

答案 2 :(得分:0)

我设法通过将发送的XML字符串转换为input.php中的变量来解决它:

$xml_data = new SimpleXMLElement(file_get_contents('php://input'));
var_dump($xml_data);

现在我可以用它做任何我想做的事。谢谢大家的尝试,你们都很棒!