cURL模拟POST方法提交XML数据并解析

php编程中会用到xml格式传送数据,这里演示下php以post形式发送xml,服务器接收,并解析xml的过程!

post_xml.php源码:

 1 <?php 
 2     header("Content-Type:text/html; charset=utf-8");
 3     //检测是否支持cURL
 4     if(!extension_loaded('curl'))
 5     {
 6         trigger_error('对不起,请开启curl功能模块!', E_USER_ERROR);
 7     }
 8     //构造xml
 9     $xmldata = <<<xml
10 <?xml version='1.0' encoding='UTF-8'?>
11     <group>
12         <name>张三</name>
13         <age>22</age>
14     </group>
15 xml;
16     //初始化curl会话
17     $ch = curl_init();
18     //设置url
19     curl_setopt($ch, CURLOPT_URL, 'http://localhost/test/deal_xml.php');
20     //设置发送方式
21     curl_setopt($ch, CURLOPT_POST, true);
22     //设置发送的数据
23     curl_setopt($ch, CURLOPT_POSTFIELDS, $xmldata);
24     //抓取URL并把它传递给浏览器
25     curl_exec($ch);
26     //关闭cURL资源,并且释放系统资源
27     curl_close($ch);
28 ?>
注:构造xml时一定要注意格式正确,不能有空格等
deal_xml.php源码:
 1 <?php 
 2     //接收传送的数据
 3     $fileContent = file_get_contents("php://input");
 4     //转换为simplexml对象
 5     $xmlResult = simplexml_load_string($fileContent);
 6     //foreach遍历循环
 7     foreach($xmlResult->children() as $childItem)
 8     {
 9         echo $childItem->getName() . '->' . $childItem . '<br/>';    //输出xml节点名称和值
10     }
11 ?>

结果:

name->张三
age->22

 
原文地址:https://www.cnblogs.com/cloak/p/4981208.html