/*
* This file is part of the overtrue/wechat.
*
* (c) overtrue
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
/**
* XML.php.
*
* Part of Overtrue\Wechat.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
*@authorovertrue
*@copyright2015 overtrue
*
*@link https://github.com/overtrue
*@link http://overtrue.me
*/
//namespace Overtrue\Wechat\Utils;
/**
* XML 工具类,用于构建与解析 XML.
*/
classXML
{
/**
* XML 转换为数组.
*
*@paramstring $xml XML string
*
*@returnarray
*/
public static functionparse($xml)
{
$data=simplexml_load_string($xml,'SimpleXMLElement',LIBXML_NOCDATA|LIBXML_NOBLANKS);
if(is_object($data) &&get_class($data) ==='SimpleXMLElement') {
$data=self::arrarval($data);
}
return$data;
}
/**
* XML编码
*
*@parammixed $data 数据
*@paramstring $root 根节点名
*@paramstring $item 数字索引的子节点名
*@paramstring $attr 根节点属性
*@paramstring $id 数字索引子节点key转换的属性名
*
*@returnstring
*/
public static functionbuild(
$data,
$root='xml',
$item='item',
$attr='',
$id='id'
) {
if(is_array($attr)) {
$_attr=array();
foreach($attras$key=>$value) {
$_attr[] ="{$key}=\"{$value}\"";
}
$attr=implode(' ',$_attr);
}
$attr=trim($attr);
$attr=empty($attr) ?'':"{$attr}";
$xml="<{$root}{$attr}>";
$xml.=self::data2Xml($data,$item,$id);
$xml.="";
return$xml;
}
/**
* 生成.
*
*@paramstring $string 内容
*
*@returnstring
*/
public static functioncdata($string)
{
returnsprintf('',$string);
}
/**
* 把对象转换成数组.
*
*@paramstring $data 数据
*
*@returnarray
*/
private static functionarrarval($data)
{
if(is_object($data) &&get_class($data) ==='SimpleXMLElement') {
$data= (array)$data;
}
if(is_array($data)) {
foreach($dataas$index=>$value) {
$data[$index] =self::arrarval($value);
}
}
return$data;
}
/**
* 转换数组为xml.
*
*@paramarray $data 数组
*@paramstring $item item的属性名
*@paramstring $id id的属性名
*
*@returnstring
*/
private static functiondata2Xml($data,$item='item',$id='id')
{
$xml=$attr='';
foreach($dataas$key=>$val) {
if(is_numeric($key)) {
$id&&$attr="{$id}=\"{$key}\"";
$key=$item;
}
$xml.="<{$key}{$attr}>";
if((is_array($val) ||is_object($val))) {
$xml.=self::data2Xml((array)$val,$item,$id);
}else{
$xml.=is_numeric($val) ?$val:self::cdata($val);
}
$xml.="";
}
return$xml;
}
}