- 浏览: 13627745 次
- 性别:
- 来自: 洛杉矶
文章分类
- 全部博客 (1994)
- Php / Pear / Mysql / Node.js (378)
- Javascript /Jquery / Bootstrap / Web (435)
- Phone / IOS / Objective-C / Swift (137)
- Ubuntu / Mac / Github / Aptana / Nginx / Shell / Linux (335)
- Perl / Koha / Ruby / Markdown (8)
- Java / Jsp (12)
- Python 2 / Wxpython (25)
- Codeigniter / CakePHP (32)
- Div / Css / XML / HTML5 (179)
- WP / Joomla! / Magento / Shopify / Drupal / Moodle / Zimbra (275)
- Apache / VPN / Software (31)
- AS3.0/2.0 / Flex / Flash (45)
- Smarty (6)
- SEO (24)
- Google / Facebook / Pinterest / SNS (80)
- Tools (22)
最新评论
-
1455975567:
xuezhongyu01 写道wocan23 写道我想问下那个 ...
Mysql: LBS实现查找附近的人 (两经纬度之间的距离) -
xuezhongyu01:
wocan23 写道我想问下那个111.1是怎么得来的我也看不 ...
Mysql: LBS实现查找附近的人 (两经纬度之间的距离) -
18335864773:
试试 pageoffice 在线打开 PDF 文件吧. pag ...
jquery在线预览PDF文件,打开PDF文件 -
青春依旧:
opacity: 0.5; 个人喜欢这种方式!关于其他css特 ...
css透明度的设置 (兼容所有浏览器) -
July01:
推荐用StratoIO打印控件,浏览器和系统的兼容性都很好,而 ...
搞定网页打印自动分页问题
XML2Array: Convert XML to Array in PHP
XML2Array is a class to convert XML to an array in PHP. It returns an array which can be converted back to XML using the Array2XML class.
It can take a string XML as input or an object of type DOMDocument
.
Conventions
- attributes stored as key value pairs under
['tag_name']['@attributes']
- CDATA nodes are stored under
['tag_name']['@cdata']
- In case a node has attributes, the value will be stored in
['tag_name']['@value']
Usage
The usage is pretty simple. You have to include the class file in your code and call the following function.
$array = XML2Array::createArray($xml); print_r($array);
Important thing to note is that the $array
returned can be converted back to XML using the Array2XML
class.
Example
The Following XML:
<?xml version="1.0" encoding="UTF-8"?> <movies type="documentary"> <movie> <title>PHP: Behind the Parser</title> <characters> <character> <name>Ms. Coder</name> <actor>Onlivia Actora</actor> </character> <character> <name>Mr. Coder</name> <actor>El ActÓr</actor> </character> </characters> <plot><![CDATA[So, this language. It's like, a programming language. Or is it a scripting language? All is revealed in this thrilling horror spoof of a documentary.]]></plot> <great-lines> <line>PHP solves all my web problems</line> </great-lines> <rating type="thumbs">7</rating> <rating type="stars">5</rating> </movie> </movies>
will generate the following output:
array ( 'movies' => array ( 'movie' => array ( 'title' => 'PHP: Behind the Parser', 'characters' => array ( 'character' => array ( 0 => array ( 'name' => 'Ms. Coder', 'actor' => 'Onlivia Actora', ), 1 => array ( 'name' => 'Mr. Coder', 'actor' => 'El ActÓr', ), ), ), 'plot' => array ( '@cdata' => 'So, this language. It\'s like, a programming language. Or is it a scripting language? All is revealed in this thrilling horror spoof of a documentary.', ), 'great-lines' => array ( 'line' => 'PHP solves all my web problems', ), 'rating' => array ( 0 => array ( '@value' => '7', '@attributes' => array ( 'type' => 'thumbs', ), ), 1 => array ( '@value' => '5', '@attributes' => array ( 'type' => 'stars', ), ), ), ), '@attributes' => array ( 'type' => 'documentary', ), ), )
Download (v0.2, 04 Mar, 2012)
The code is released under Apache License 2.0
Plain text PHP source | Formatted PHP source
来源: http://www.lalit.org/lab/convert-xml-to-array-in-php-xml2array/
源码:
<?php /** * XML2Array: A class to convert XML to array in PHP * It returns the array which can be converted back to XML using the Array2XML script * It takes an XML string or a DOMDocument object as an input. * * See Array2XML: http://www.lalit.org/lab/convert-php-array-to-xml-with-attributes * * Author : Lalit Patel * Website: http://www.lalit.org/lab/convert-xml-to-array-in-php-xml2array * License: Apache License 2.0 * http://www.apache.org/licenses/LICENSE-2.0 * Version: 0.1 (07 Dec 2011) * Version: 0.2 (04 Mar 2012) * Fixed typo 'DomDocument' to 'DOMDocument' * * Usage: * $array = XML2Array::createArray($xml); */ class XML2Array { private static $xml = null; private static $encoding = 'UTF-8'; /** * Initialize the root XML node [optional] * @param $version * @param $encoding * @param $format_output */ public static function init($version = '1.0', $encoding = 'UTF-8', $format_output = true) { self::$xml = new DOMDocument($version, $encoding); self::$xml->formatOutput = $format_output; self::$encoding = $encoding; } /** * Convert an XML to Array * @param string $node_name - name of the root node to be converted * @param array $arr - aray to be converterd * @return DOMDocument */ public static function &createArray($input_xml) { $xml = self::getXMLRoot(); if(is_string($input_xml)) { $parsed = $xml->loadXML($input_xml); if(!$parsed) { throw new Exception('[XML2Array] Error parsing the XML string.'); } } else { if(get_class($input_xml) != 'DOMDocument') { throw new Exception('[XML2Array] The input XML object should be of type: DOMDocument.'); } $xml = self::$xml = $input_xml; } $array[$xml->documentElement->tagName] = self::convert($xml->documentElement); self::$xml = null; // clear the xml node in the class for 2nd time use. return $array; } /** * Convert an Array to XML * @param mixed $node - XML as a string or as an object of DOMDocument * @return mixed */ private static function &convert($node) { $output = array(); switch ($node->nodeType) { case XML_CDATA_SECTION_NODE: $output['@cdata'] = trim($node->textContent); break; case XML_TEXT_NODE: $output = trim($node->textContent); break; case XML_ELEMENT_NODE: // for each child node, call the covert function recursively for ($i=0, $m=$node->childNodes->length; $i<$m; $i++) { $child = $node->childNodes->item($i); $v = self::convert($child); if(isset($child->tagName)) { $t = $child->tagName; // assume more nodes of same kind are coming if(!isset($output[$t])) { $output[$t] = array(); } $output[$t][] = $v; } else { //check if it is not an empty text node if($v !== '') { $output = $v; } } } if(is_array($output)) { // if only one node of its kind, assign it directly instead if array($value); foreach ($output as $t => $v) { if(is_array($v) && count($v)==1) { $output[$t] = $v[0]; } } if(empty($output)) { //for empty nodes $output = ''; } } // loop through the attributes and collect them if($node->attributes->length) { $a = array(); foreach($node->attributes as $attrName => $attrNode) { $a[$attrName] = (string) $attrNode->value; } // if its an leaf node, store the value in @value instead of directly storing it. if(!is_array($output)) { $output = array('@value' => $output); } $output['@attributes'] = $a; } break; } return $output; } /* * Get the root XML node, if there isn't one, create it. */ private static function getXMLRoot(){ if(empty(self::$xml)) { self::init(); } return self::$xml; } } ?>
Array2XML: convert PHP Array to XML (with attributes and CDATA)
Array2XML is a class to convert an array in PHP to XML. It allows you to parse a multidimensional array into XML including attributes unlike other scripts available on the internet. It returns the XML in form of DOMDocument object for further manipulation.
This library is very helpful when you know the scheme before hand and you have to generate an XML for it using dynamic values from the database.
The resulting XML can be converted back to an Array using the XML2Array class.
Usage
The usage is pretty simple. You have to include the class file in your code and call the following function.
$xml = Array2XML::createXML('root_node_name', $php_array); echo $xml->saveXML();
Important thing to note is that the $xml
object returned is of type DOMDocument
and hence you can perform further operations on it.
Optionally you can also set the version of XML and encoding by calling the Array2XML::init()
function before calling the Array2XML::createXML()
function.
Array2XML::init($version /* ='1.0' */, $encoding /* ='UTF-8' */);
It throws exception if the tag name or attribute name has illegal chars as per W3C spec .
Array Structure conventions
The array passed to the Array2XML::createXML()
function follows few conventions, which are quite literal and easy to learn/use. The examples below demonstrate their usage
1. Empty Nodes: Following will create an empty node.
$books = array(); // or $books = null; // or $books = ''; $xml = Array2XML::createXML('books', $books); // all three cases above create <books/>
2. Attributes:
Attributes can be added to any node by having a @attributes
key in the array
$books = array( '@attributes' => array( 'type' => 'fiction', 'year' => 2011, 'bestsellers' => true ) ); $xml = Array2XML::createXML('books', $books); // creates <books type="fiction" year="2011" bestsellers="true"/>
3. Node Value:
For nodes without attributes, value can be assigned directly, else we need to have a @value
key in the array. Following examples will make it clear
$books = 1984; // or $books = array( '@value' = 1984 ); // creates <books>1984</books> $books = array( '@attributes' => array( 'type' => 'fiction' ), '@value' = 1984 ); // creates <books type="fiction">1984</books> $books = array( '@attributes' => array( 'type' => 'fiction' ), 'book' => 1984 ); /* creates <books type="fiction"> <book>1984</book> </books> */ $books = array( '@attributes' => array( 'type' => 'fiction' ), 'book'=> array('1984','Foundation','Stranger in a Strange Land') ); /* creates <books type="fiction"> <book>1984</book> <book>Foundation</book> <book>Stranger in a Strange Land</book> </books> */
4. Complex XML: Following example clarifies most of the usage of the library
$books = array( '@attributes' => array( 'type' => 'fiction' ), 'book' => array( array( '@attributes' => array( 'author' => 'George Orwell' ), 'title' => '1984' ), array( '@attributes' => array( 'author' => 'Isaac Asimov' ), 'title' => array('@cdata'=>'Foundation'), 'price' => '$15.61' ), array( '@attributes' => array( 'author' => 'Robert A Heinlein' ), 'title' => array('@cdata'=>'Stranger in a Strange Land'), 'price' => array( '@attributes' => array( 'discount' => '10%' ), '@value' => '$18.00' ) ) ) ); /* creates <books type="fiction"> <book author="George Orwell"> <title>1984</title> </book> <book author="Isaac Asimov"> <title><![CDATA[Foundation]]></title> <price>$15.61</price> </book> <book author="Robert A Heinlein"> <title><![CDATA[Stranger in a Strange Land]]</title> <price discount="10%">$18.00</price> </book> </books> */
Detailed Example
You can see a much more detailed example here .
Download (v0.8, 2 May, 2012)
The code is released under Apache License 2.0
Plaint text PHP source | Formatted PHP source
来源: http://www.lalit.org/lab/convert-php-array-to-xml-with-attributes/
源码:
<?php /** * Array2XML: A class to convert array in PHP to XML * It also takes into account attributes names unlike SimpleXML in PHP * It returns the XML in form of DOMDocument class for further manipulation. * It throws exception if the tag name or attribute name has illegal chars. * * Author : Lalit Patel * Website: http://www.lalit.org/lab/convert-php-array-to-xml-with-attributes * License: Apache License 2.0 * http://www.apache.org/licenses/LICENSE-2.0 * Version: 0.1 (10 July 2011) * Version: 0.2 (16 August 2011) * - replaced htmlentities() with htmlspecialchars() (Thanks to Liel Dulev) * - fixed a edge case where root node has a false/null/0 value. (Thanks to Liel Dulev) * Version: 0.3 (22 August 2011) * - fixed tag sanitize regex which didn't allow tagnames with single character. * Version: 0.4 (18 September 2011) * - Added support for CDATA section using @cdata instead of @value. * Version: 0.5 (07 December 2011) * - Changed logic to check numeric array indices not starting from 0. * Version: 0.6 (04 March 2012) * - Code now doesn't @cdata to be placed in an empty array * Version: 0.7 (24 March 2012) * - Reverted to version 0.5 * Version: 0.8 (02 May 2012) * - Removed htmlspecialchars() before adding to text node or attributes. * * Usage: * $xml = Array2XML::createXML('root_node_name', $php_array); * echo $xml->saveXML(); */ class Array2XML { private static $xml = null; private static $encoding = 'UTF-8'; /** * Initialize the root XML node [optional] * @param $version * @param $encoding * @param $format_output */ public static function init($version = '1.0', $encoding = 'UTF-8', $format_output = true) { self::$xml = new DomDocument($version, $encoding); self::$xml->formatOutput = $format_output; self::$encoding = $encoding; } /** * Convert an Array to XML * @param string $node_name - name of the root node to be converted * @param array $arr - aray to be converterd * @return DomDocument */ public static function &createXML($node_name, $arr=array()) { $xml = self::getXMLRoot(); $xml->appendChild(self::convert($node_name, $arr)); self::$xml = null; // clear the xml node in the class for 2nd time use. return $xml; } /** * Convert an Array to XML * @param string $node_name - name of the root node to be converted * @param array $arr - aray to be converterd * @return DOMNode */ private static function &convert($node_name, $arr=array()) { //print_arr($node_name); $xml = self::getXMLRoot(); $node = $xml->createElement($node_name); if(is_array($arr)){ // get the attributes first.; if(isset($arr['@attributes'])) { foreach($arr['@attributes'] as $key => $value) { if(!self::isValidTagName($key)) { throw new Exception('[Array2XML] Illegal character in attribute name. attribute: '.$key.' in node: '.$node_name); } $node->setAttribute($key, self::bool2str($value)); } unset($arr['@attributes']); //remove the key from the array once done. } // check if it has a value stored in @value, if yes store the value and return // else check if its directly stored as string if(isset($arr['@value'])) { $node->appendChild($xml->createTextNode(self::bool2str($arr['@value']))); unset($arr['@value']); //remove the key from the array once done. //return from recursion, as a note with value cannot have child nodes. return $node; } else if(isset($arr['@cdata'])) { $node->appendChild($xml->createCDATASection(self::bool2str($arr['@cdata']))); unset($arr['@cdata']); //remove the key from the array once done. //return from recursion, as a note with cdata cannot have child nodes. return $node; } } //create subnodes using recursion if(is_array($arr)){ // recurse to get the node for that key foreach($arr as $key=>$value){ if(!self::isValidTagName($key)) { throw new Exception('[Array2XML] Illegal character in tag name. tag: '.$key.' in node: '.$node_name); } if(is_array($value) && is_numeric(key($value))) { // MORE THAN ONE NODE OF ITS KIND; // if the new array is numeric index, means it is array of nodes of the same kind // it should follow the parent key name foreach($value as $k=>$v){ $node->appendChild(self::convert($key, $v)); } } else { // ONLY ONE NODE OF ITS KIND $node->appendChild(self::convert($key, $value)); } unset($arr[$key]); //remove the key from the array once done. } } // after we are done with all the keys in the array (if it is one) // we check if it has any text value, if yes, append it. if(!is_array($arr)) { $node->appendChild($xml->createTextNode(self::bool2str($arr))); } return $node; } /* * Get the root XML node, if there isn't one, create it. */ private static function getXMLRoot(){ if(empty(self::$xml)) { self::init(); } return self::$xml; } /* * Get string representation of boolean value */ private static function bool2str($v){ //convert boolean to text value. $v = $v === true ? 'true' : $v; $v = $v === false ? 'false' : $v; return $v; } /* * Check if the tag name or attribute name contains illegal characters * Ref: http://www.w3.org/TR/xml/#sec-common-syn */ private static function isValidTagName($tag){ $pattern = '/^[a-z_]+[a-z0-9\:\-\.\_]*[^:]*$/i'; return preg_match($pattern, $tag, $matches) && $matches[0] == $tag; } } ?>
发表评论
-
PHP: 在类(class)中加载动态函数, 变量函数或半变量函数 variable function/method
2016-09-03 07:54 7086最终实例在下方 以前 ... -
MySQL入门 (七) : 储存引擎与资料型态
2016-09-03 07:49 44991 表格与储存引擎 表格(table)是资料库中用来储存 ... -
MySQL入门 (六) : 字元集与资料库
2016-09-03 07:47 44951 Character Set与Collation 任何 ... -
MySQL入门 (五) : CRUD 与资料维护
2016-09-03 07:46 54111 取得表格资讯 1.1 DESCRIBE指令 「 ... -
MySQL入门 (四) : JOIN 与UNION 查询
2016-09-03 07:42 44331 使用多个表格 在「world」资料库的「countr ... -
PHP: 关键字global 和 超全局变量$GLOBALS的用法、解释、区别
2016-08-31 12:07 4974$GLOBALS 是一个关联数组,每一个变量为一个 ... -
MySQL入门 (三) : 运算式与函式
2016-08-31 12:01 4321运算式(expressions)已经 ... -
MySQL入门 (二) : SELECT 基础查询
2016-08-31 11:56 46261 查询资料前的基本概念 1.1 表格、纪录 ... -
MySQL入门 (一) : 资料库概论与MySQL的安装
2016-08-31 11:51 43881. 储存与管理资料 储存与管理资料一直是资讯应用上最基本 ... -
MySQL入门 (九) : 子查询 Subquery
2016-08-30 02:26 43911 一个叙述中的查询叙述 子查询(subquery)是一 ... -
PHP: 用readonly取代disabled来获取input值 submit a disabled input in a form could not ge
2016-08-30 02:21 2643The form is like below; <f ... -
PHP7革新与性能优化
2016-08-30 02:20 2090有幸参与2015年的PHP技 ... -
Mysql: 图解 inner join、left join、right join、full outer join、union、union all的区别
2016-08-18 06:03 3063对于SQL的Join,在学习起来可能是比较乱的。我们知道, ... -
Comet 反Ajax: 基于jQuery与PHP实现Ajax长轮询(LongPoll)
2016-08-18 06:00 1322传统的AJAX轮询方式,客服端以用户定义的时间间隔去服务器上 ... -
PHP:ServerPush (Comet推送) 技术的探讨
2016-08-18 05:58 985PHP中Push(推送)技术的探讨 [http://vi ... -
PHP: 手把手编写自己的 MVC 框架实例教程
2016-08-16 05:33 17571 什么是MVC MVC模式(Model-View-Con ... -
PHP5: mysqli 插入, 查询, 更新和删除 Insert Update Delete Using mysqli (CRUD)
2016-07-29 12:55 1694原文: PHP5: mysqli 插入, 查询, 更新 ... -
MongoDB 教程索引 (附有视频)
2016-07-27 10:54 688MongoDB 教程索引 MongoDB 教程一: ... -
Node.js 模块之Nimble流程控制
2016-07-18 12:59 1034NodeJS异步的特性有时候 ... -
Node.js web应用模块之Supervisor
2016-07-18 12:56 2279在开发或调试Node.js应 ...
相关推荐
jdk升级之后出现异常:java.lang.NoClassDefFoundError: javax/xml/ws/Service 1、解决方案jdk降级至1.8之前 2、由于JDK9以后,去除了javax.xml包需要引入对应的jar包 <groupId>javax.activation</groupId> ...
jdk升级jdk10后,原本jdk自带的 webservice一些包确实,引起的一系列错误解决方案
本类支持无限极数组生成xml,或者xml生成数组
为PHP4.0以上的数组自动生成xml类文件
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd
xml转json,或xml转array xml转json,或xml转array
超轻量级 JSON / XML / YAML 解析门面 API,用法简单,不依赖具体的 JSON / XML / YAML 实现
使用java工具xml2axml.jar反编译AndroidManafest文件 通过xml2axml.jar工具反编译AndroidManafest文件 还原AndroidManafest.xml详细过程: 1、获取到apk 2、解压获取里面的AndroidManifest.xml文件 3、在xml2axml....
本篇文章是对array2xml和xml2array以及xml与array的互相转化进行了详细的分析介绍,需要的朋友参考下
· 第一章:XML快速入门 · 一. 什么是XML? · 二. XML是新概念吗? · 三. 使用XML有什么好处? · 四. XML很难学吗? · 五. XML和HTML的区别 · 六. XML的严格格式 · 七. 关于XML的更多 · 第二章:XML概念 ...
最新的SQL/XML标准,介绍了SQL所支持的XML数据类型,XML函数等等。
XML与JavaBean互换文件 XML与JavaBean互换文件 XML与JavaBean互换文件 XML与JavaBean互换文件
图片和XML格式互换,非常简单,一看就明白。
2.xml文件是由元素和元素的内容以及属性组成的,一个xml文件中只能有一个根元素,标签和标签的内容加在一起叫作一个元素。xml是大小写 敏感的,只能以字母或下划线开头。 字符转义 < 代表 ", > 代表 ">" , &...
可以快速批量生成HTML/XML/WORD文档/EXCEL文档的简易模板库,模板库为C语言实现,非常简单,只有一个文件。能够按照模板格式生成HTML/XML/WORD文档/EXCEL文档等等各种文档。比如,需要批量生成报表、单据、静态网页...
composer require spatie/array-to-xml用法use Spatie \ ArrayToXml \ ArrayToXml ;. . .$ array = [ 'Good guy' => [ 'name' => 'Luke Skywalker' , 'weapon' => 'Lightsaber' ], 'Bad guy' => [ 'name' => '...
* @example $my_web2xml = new C_Web2XML('/bbs','bbs.xml');$my_web2xml->Set_FileExtendFiler('exe|rar|zip');$my_web2xml->Create_Web2XML(); * @desc Covert the XML file to you website * @example $my_web...
HTML/XML 解析器类库.zip,Kanna(鉋) is an XML/HTML parser for Swift.
主是描述了在php下array与Xml之间的转换总结,文档内有部分代码讲解!
在jsp运行过程中,报错 java.lang.NoClassDefFoundError org.apache.xml.serializer.TreeWalker时的处理方法。