php接收xml文件数据并返回xml

接收文件并转成xml格式

// 监听获取数据传入
$xml_str = file_get_contents('php://input');
// 获取文件格式
$content_type = filter_input(INPUT_SERVER, "CONTENT_TYPE");
// 将文件转成xml格式,并存储原文件标识
switch ($content_type) {
    case 'application/x-compress-zlib' :
        $xml_str = gzuncompress($xml_str);
        $compressmode = "zlib";
        break;
    case 'Content-Type: application/x-compress-gzip' :
        $xml_str = gzdecode($xml_str);
        $compressmode = "gzip";
        break;
    default :
        $compressmode = "none";
}

将xml格式字符串转成simplexml对象,再将simplexml对象转成数组

 // xml字符串转换为simplexml对象
$xml = @simplexml_load_string($xml_str, 'SimpleXMLElement', LIBXML_NOCDATA);
if (!$xml) { // xml结构不完整
    $return_xml->addChild('ERROR','XML结构不完整!');
} else {
	// xml转array(或为:json_decode(json_encode((array)$xml), true);)
    $array = json_decode(json_encode($xml), true); 
}

创建返回的simplexml对象

$return_xml = "<?xml version='1.0' encoding='UTF-8'?>
<REPLY>
</REPLY>";
$return_xml = @simplexml_load_string($return_xml, 'SimpleXMLElement', LIBXML_NOCDATA);

向返回的simplexml对象添加key-value

$return_xml->addChild($key, $val);
$return_xml->addChild('ERROR','参数未知!');

返回相应格式xml文件

// 返回xml文件
switch ($compressmode) {
    case 'none' :
        header("Content-Type: application/xml");
        echo $return_xml->asXML();
        break;
    case 'zlib' :
        header("Content-Type: application/x-compress-zlib");
        echo gzcompress($return_xml->asXML());
        break;
    case 'gzip' :
        header("Content-Type: application/x-compress-gzip");
        echo gzencode($return_xml->asXML());
        break;
    default :
        echo "未知文件格式!";
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值