您的位置:首页 > 其它

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

2015-11-20 16:26 525 查看
php编程中会用到xml格式传送数据,这里演示下php以post形式发送xml,服务器接收,并解析xml的过程!

post_xml.php源码:

<?php
header("Content-Type:text/html; charset=utf-8");
//检测是否支持cURL
if(!extension_loaded('curl'))
{
trigger_error('对不起,请开启curl功能模块!', E_USER_ERROR);
}
//构造xml
$xmldata = <<<xml
<?xml version='1.0' encoding='UTF-8'?>
<group>
<name>张三</name>
<age>22</age>
</group>
xml;
//初始化curl会话
$ch = curl_init();
//设置url
curl_setopt($ch, CURLOPT_URL, 'http://localhost/test/deal_xml.php');
//设置发送方式
curl_setopt($ch, CURLOPT_POST, true);
//设置发送的数据
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmldata);
//抓取URL并把它传递给浏览器
curl_exec($ch);
//关闭cURL资源,并且释放系统资源
curl_close($ch);
?>


注:构造xml时一定要注意格式正确,不能有空格等
deal_xml.php源码:


<?php
//接收传送的数据
$fileContent = file_get_contents("php://input");
//转换为simplexml对象
$xmlResult = simplexml_load_string($fileContent);
//foreach遍历循环
foreach($xmlResult->children() as $childItem)
{
echo $childItem->getName() . '->' . $childItem . '<br/>';    //输出xml节点名称和值
}
?>


结果:

name->张三
age->22


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: