php xml

/*

* 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;

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Correctness AdapterViewChildren Summary: AdapterViews can...
    MarcusMa阅读 8,912评论 0 6
  • 1. XML Expat 解析器(基于事件) 工作原理 使用的xml文件test.xml 通过 xml_parse...
    BelleChen阅读 207评论 0 1
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,765评论 18 399
  • 整体结构 自己没有怎么花时间画图,怕可能有遗漏的地方所以,先参考一下别人的代码分析(之前的内容,应该没有雷同的地方...
    dodo_lihao阅读 650评论 0 2
  • 老友来电,晚上空吗?见个面吧。当接到她约见面的电话时,我会惯性的撇开所有安排,去见她。每次见面,放松自在,海阔天空...
    仁素阅读 131评论 0 0