This Simplexml class provides an alternative implementation of the SimpleXML API that works under PHP 4, so if you have an application that is running under PHP4 environment this is really helpful for you.

The original class was created by Taha Paksu of http://www.phpclasses.org and it was modified by Chris Brainard so that it would work with codeigniter.

Lets take a look at the code.

  1. <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
  2. class Simplexml{
  3. var $result = array();
  4. var $ignore_level = 0;
  5. var $skip_empty_values = false;
  6. var $php_errormsg;
  7. var $evalCode="";
  8. function xml_parse($data){
  9. $php_errormsg="";
  10. $this->result="";
  11. $this->evalCode="";
  12. $values="";
  13. $encoding = 'UTF-8';
  14. $parser = xml_parser_create($encoding);
  15. xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  16. xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
  17. $ok = xml_parse_into_struct($parser, $data, $values);
  18. if (!$ok) {
  19. $errmsg = sprintf("XML parse error %d '%s' at line %d, column %d (byte index %d)",
  20. xml_get_error_code($parser),
  21. xml_error_string(xml_get_error_code($parser)),
  22. xml_get_current_line_number($parser),
  23. xml_get_current_column_number($parser),
  24. xml_get_current_byte_index($parser));
  25. }
  26. xml_parser_free($parser);
  27. return $this->xml_reorganize($values);
  28. }
  29. function xml_reorganize($array)
  30. {
  31. $count = count($array);
  32. $repeat = $this->xml_tags($array);
  33. $repeatedone = false;
  34. $tags = array();
  35. $k = 0;
  36. for ($i = 0; $i < $count; $i++) {
  37. switch ($array[$i]['type']) {
  38. case 'open':
  39. array_push($tags, $array[$i]['tag']);
  40. if ($i > 0 && ($array[$i]['tag'] == $array[$i-1]['tag']) && ($array[$i-1]['type'] == 'close'))
  41. $k++;
  42. if (isset($array[$i]['value']) && ($array[$i]['value'] || !$this->skip_empty_values)) {
  43. array_push($tags, '@content');
  44. $this->array_insert(count($tags), $tags, $array[$i]['value'], "open");
  45. array_pop($tags);
  46. }
  47. if (in_array($array[$i]['tag'] . $array[$i]['level'], $repeat)) {
  48. if (($repeatedone == $array[$i]['tag'] . $array[$i]['level']) && ($repeatedone)) {
  49. array_push($tags, strval($k++));
  50. } else {
  51. $repeatedone = $array[$i]['tag'] . $array[$i]['level'];
  52. array_push($tags, strval($k));
  53. }
  54. }
  55. if (isset($array[$i]['attributes']) && $array[$i]['attributes'] && $array[$i]['level'] != $this->ignore_level) {
  56. array_push($tags, '@attributes');
  57. foreach ($array[$i]['attributes'] as $attrkey => $attr) {
  58. array_push($tags, $attrkey);
  59. $this->array_insert(count($tags), $tags, $attr, "open");
  60. array_pop($tags);
  61. }
  62. array_pop($tags);
  63. }
  64. break;
  65. case 'close':
  66. array_pop($tags);
  67. if (in_array($array[$i]['tag'] . $array[$i]['level'], $repeat)) {
  68. if ($repeatedone == $array[$i]['tag'] . $array[$i]['level']) {
  69. array_pop($tags);
  70. } else {
  71. $repeatedone = $array[$i + 1]['tag'] . $array[$i + 1]['level'];
  72. array_pop($tags);
  73. }
  74. }
  75. break;
  76. case 'complete':
  77. array_push($tags, $array[$i]['tag']);
  78. if (in_array($array[$i]['tag'] . $array[$i]['level'], $repeat)) {
  79. if ($repeatedone == $array[$i]['tag'] . $array[$i]['level'] && $repeatedone) {
  80. array_push($tags, strval($k));
  81. } else {
  82. $repeatedone = $array[$i]['tag'] . $array[$i]['level'];
  83. array_push($tags, strval($k));
  84. }
  85. }
  86. if (isset($array[$i]['value']) && ($array[$i]['value'] || !$this->skip_empty_values)) {
  87. if (isset($array[$i]['attributes']) && $array[$i]['attributes']) {
  88. array_push($tags, '@content');
  89. $this->array_insert(count($tags), $tags, $array[$i]['value'], "complete");
  90. array_pop($tags);
  91. } else {
  92. $this->array_insert(count($tags), $tags, $array[$i]['value'], "complete");
  93. }
  94. }
  95. if (isset($array[$i]['attributes']) && $array[$i]['attributes']) {
  96. array_push($tags, '@attributes');
  97. foreach ($array[$i]['attributes'] as $attrkey => $attr) {
  98. array_push($tags, $attrkey);
  99. $this->array_insert(count($tags), $tags, $attr, "complete");
  100. array_pop($tags);
  101. }
  102. array_pop($tags);
  103. }
  104. if (in_array($array[$i]['tag'] . $array[$i]['level'], $repeat)) {
  105. array_pop($tags);
  106. $k++;
  107. }
  108. array_pop($tags);
  109. break;
  110. }
  111. }
  112. eval($this->evalCode);
  113. $last = $this->array_reindex($this->result);
  114. return $last;
  115. }
  116. function array_insert($level, $tags, $value, $type)
  117. {
  118. $temp = '';
  119. for ($c = $this->ignore_level + 1; $c < $level + 1; $c++) {
  120. if (isset($tags[$c]) && (is_numeric(trim($tags[$c])) || trim($tags[$c]))) {
  121. if (is_numeric($tags[$c])) {
  122. $temp .= '[' . $tags[$c] . ']';
  123. } else {
  124. $temp .= '["' . $tags[$c] . '"]';
  125. }
  126. }
  127. }
  128. $this->evalCode .= '$this->result' . $temp . "=\"" . addslashes($value) . "\";//(" . $type . ")\n";
  129. #echo $code. "\n";
  130. }
  131. /**
  132. * Define the repeated tags in XML file so we can set an index
  133. *
  134. * @param array $array
  135. * @return array
  136. */
  137. function xml_tags($array)
  138. {   $repeats_temp = array();
  139. $repeats_count = array();
  140. $repeats = array();
  141. if (is_array($array)) {
  142. $n = count($array) - 1;
  143. for ($i = 0; $i < $n; $i++) {
  144. $idn = $array[$i]['tag'].$array[$i]['level'];
  145. if(in_array($idn,$repeats_temp)){
  146. $repeats_count[array_search($idn,$repeats_temp)]+=1;
  147. }else{
  148. array_push($repeats_temp,$idn);
  149. $repeats_count[array_search($idn,$repeats_temp)]=1;
  150. }
  151. }
  152. }
  153. $n = count($repeats_count);
  154. for($i=0;$i<$n;$i++){
  155. if($repeats_count[$i]>1){
  156. array_push($repeats,$repeats_temp[$i]);
  157. }
  158. }
  159. unset($repeats_temp);
  160. unset($repeats_count);
  161. return array_unique($repeats);
  162. }
  163. /**
  164. * Converts Array Variable to Object Variable
  165. *
  166. * @param array $arg_array
  167. * @return $tmp
  168. */
  169. function array2object ($arg_array)
  170. {
  171. if (is_array($arg_array)) {
  172. $keys = array_keys($arg_array);
  173. if(!is_numeric($keys[0])) $tmp = new Xml;
  174. foreach ($keys as $key) {
  175. if (is_numeric($key)) $has_number = true;
  176. if (is_string($key)) $has_string = true;
  177. }
  178. if (isset($has_number) and !isset($has_string)) {
  179. foreach ($arg_array as $key => $value) {
  180. $tmp[] = $this->array2object($value);
  181. }
  182. } elseif (isset($has_string)) {
  183. foreach ($arg_array as $key => $value) {
  184. if (is_string($key))
  185. $tmp->$key = $this->array2object($value);
  186. }
  187. }
  188. } elseif (is_object($arg_array)) {
  189. foreach ($arg_array as $key => $value) {
  190. if (is_array($value) or is_object($value))
  191. $tmp->$key = $this->array2object($value);
  192. else
  193. $tmp->$key = $value;
  194. }
  195. } else {
  196. $tmp = $arg_array;
  197. }
  198. return $tmp; //return the object
  199. }
  200. /**
  201. * Reindexes the whole array with ascending numbers
  202. *
  203. * @param array $array
  204. * @return array
  205. */
  206. function array_reindex($array)
  207. {
  208. if (is_array($array)) {
  209. if(count($array) == 1 && $array[0]){
  210. return $this->array_reindex($array[0]);
  211. }else{
  212. foreach($array as $keys => $items) {
  213. if (is_array($items)) {
  214. if (is_numeric($keys)) {
  215. $array[$keys] = $this->array_reindex($items);
  216. } else {
  217. $array[$keys] = $this->array_reindex(array_merge(array(), $items));
  218. }
  219. }
  220. }
  221. }
  222. }
  223. return $array;
  224. }
  225. }

In this article we don’t need to understand what is in the code above. What is my aim is to show you how to use it.

Supposing you have an xml format like below, and you need it to present as a tabular data in an html page.

  1. <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  2. <products xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  3. <item>
  4. <id>1</id>
  5. <name>iPhone</name>
  6. <category>Mobile</category>
  7. <price>300</price>
  8. </item>
  9. <item>
  10. <id>2</id>
  11. <name>iMac</name>
  12. <category>Desktop Computers</category>
  13. <price>2500</price>
  14. </item>
  15. <item>
  16. <id>3</id>
  17. <name>MacBook Pro</name>
  18. <category>Mobile PC</category>
  19. <price>2000</price>
  20. </item>
  21. <item>
  22. <id>4</id>
  23. <name>iTouch</name>
  24. <category>Gadgets</category>
  25. <price>150</price>
  26. </item>
  27. <item>
  28. <id>5</id>
  29. <name>Wii</name>
  30. <category>Gaming</category>
  31. <price>1250</price>
  32. </item>
  33. <item>
  34. <id>6</id>
  35. <name>Time Capsule</name>
  36. <category>Acessories</category>
  37. <price>1000</price>
  38. </item>
  39. <item>
  40. <id>7</id>
  41. <name>Apple TV</name>
  42. <category>Gadgets</category>
  43. <price>800</price>
  44. </item>
  45. </products>

Lets start by creating our controller, to make it easier lets make use of the default controller in fresh CI installation which is the welcome controller. Now open you welcome controller and in you index function populate the code below.

  1. function index()
  2. {
  3. //load the parser library
  4. $this->load->library('parser');
  5. $data['title'] = 'Parsing XML using Simplexml class of CodeIgniter';
  6. $data['products'] = $this->_getXML('myxml');
  7. $this->parser->parse('table_view', $data);
  8. }

In this function we load the parser library, for those who dont know what a parser library is, its a simple templating engine of codeIgniter. Im using this almost always for me to get rid if the php tag in my view. Next we have a varialble title , and a variable products which calls the _getXML function with a string parametermyxml , we use this as reference of the filename for our XML file to be parse. Then load our table_view .

Lets add the _getXML function to our controller. Add this code in your welcome controller.

  1. function _getXML($fname)
  2. {
  3. $filename = $fname.'.xml';
  4. $xmlfile="./xml/".$filename;
  5. $xmlRaw = file_get_contents($xmlfile);
  6. $this->load->library('simplexml');
  7. $xmlData = $this->simplexml->xml_parse($xmlRaw);
  8. foreach($xmlData['item'] as $row)
  9. {
  10. $result .= '<tr>';
  11. $result .= '<td>'.$row['id'].'</td>';
  12. $result .= '<td>'.$row['name'].'</td>';
  13. $result .= '<td>'.$row['category'].'</td>';
  14. $result .= '<td>$ '.$row['price'].'</td>';
  15. $result .= '</tr>';
  16. }
  17. return $result;
  18. }

This assume that the file location of your xml file is in the root of your CI installation an inside the xml folder. Then using the file_get_contents() function we load the xml data to $xmlRaw varialble. We loaded the simple XML library and then we populate it to the table element using foreach() function.

Now you only need to add a very little code in your view file.

  1. <table cellpadding="0" cellspacing="0">
  2. <thead>
  3. <th>
  4. <td>PRODUCT ID</td>
  5. <td>PRODUCT NAME</td>
  6. <td>CATEGORY</td>
  7. <td>PRICE</td>
  8. </th>
  9. </thead>
  10. <tbody>
  11. {products}
  12. </tbody>
  13. </table>

Thats it!. Adding some quick css styling and a jQuery for table row stripe effect. You get something like this.

Adding a quick table stripe effect.

Download and include the jQuery library file in your view.

  1. <script type="text/javascript" src="public/js/jquery.js"></script>

Then add this line before the tag in your view file.

  1. <script type="text/javascript">
  2. $(document).ready(function(){
  3. $("table tr:nth-child(even)").addClass("even");
  4. });
  5. </script>

And you must have a style like this in your css file.

  1. table tr.even td{
  2. background: #cdded6;
  3. }

Were done. Thanks for reading.

--------------------------------------------------------------链接:

http://justcoding.iteye.com/blog/558775

http://blog.insicdesigns.com/2009/03/parsing-xml-file-using-codeigniters-simplexml-library/

BUG修改:

Q:

nice work and really working fine please can you update this library because i have seen in comments 
if(count($array) == 1 && isset($array[0]))

please upate it.

A:

change this line if(count($array) == 1 && $array[0]){

to below line..this line exist in library function is "array_reindex" (line no 230)

if(count($array) == 1 && array_key_exists(0, $array)){

***codeigniter操作xml(Simplexml第三方扩展)的更多相关文章

  1. C#操作Xml树的扩展类

    本文提供一个操作Xml树的扩展类,与将xml字符串直接映射成实体对象的使用方法,供大家参考,学习. 下面附上源码 using System; using System.Collections.Gene ...

  2. PHP操作XML方法之SimpleXML

    SimpleXML简介 SimpleXML 扩展提供了一个非常简单和易于使用的工具集,能将XML转换成一个带有一般属性选择器和数组迭代器的对象. 举例XML XML结构部分引用自<<深入理 ...

  3. php simpleXML操作xml的用法

    XML简介 XML是一种流行的半结构化文件格式,以一种类似数据库的格式存储数据.在实际应用中,一些简单的.安全性较低的数据往往使用 XML文件的格式进行存储.这样做的好处一方面可以通过减少与数据库的交 ...

  4. XMl入门介绍及php操作XML

    一.什么是XML XML全称:Extensible Markup Language 中文名:可扩展标记语言 用于标记电子文件使其具有结构性的标记语言,可以用来标记数据,定义数据类型,允许用户对自己的标 ...

  5. delphi操作xml学习笔记 之一 入门必读

    Delphi 对XML的支持---TXMLDocument类       Delphi7 支持对XML文档的操作,可以通过TXMLDocument类来实现对XML文档的读写.可以利用TXMLDocum ...

  6. php : DOM 操作 XML

    DOM 操作 XML 基本用法 XML文件: person.XML <?xml version="1.0" encoding="utf-8" ?> ...

  7. php操作xml

    最近计划写个人的小网站,一系列原因选择了用php来写,最大的问题就是虽然php很流行,但我从来没有接触过php,看了一个多星期的基本语法后做些小练习热热身,但是期间是各种问题啊,主要是对php不熟悉, ...

  8. 让时间处理简单化 【第三方扩展类库org.apache.commons.lang.time】

    JAVA的时间日期处理一直是一个比较复杂的问题,大多数程序员都不能很轻松的来处理这些问题.首先Java中关于时间的类,从 JDK 1.1 开始,Date的作用很有限,相应的功能已由Calendar与D ...

  9. Delphi操作XML简介

    参考:http://www.delphifans.com/InfoView/Article_850.html Delphi 7支持对XML文档的操作,可以通过 TXMLDocument类来实现对XML ...

随机推荐

  1. VS2013配置 OpenCV3.0【实测有效】

    下载OpenCV3.0.0 到OpenCV官网下载对应版本http://opencv.org/downloads.html,然后安装到相应目录,本例是安装到D:\opencv300目录中. 配置环境变 ...

  2. nandflash,norflash,sdram,emmc,rom,ram等各种存储器识别

    老是被nandflash,norflash,sdram,emmc,rom,ram搞混,所以在这里总结一下,也为了更好的分清他们之间的关系,以至于别人问的时候不至于说不清. 我们不谈这些名次的由来,只说 ...

  3. HDU 1564 简单博弈 水

    n*n棋盘,初始左上角有一个石头,每次放只能在相邻的四个位置之一,不能操作者输. 如果以初始石头编号为1作为后手,那么对于每次先手胜的情况其最后一步的四周的编号必定是奇数,且此时编号为偶数,而对于一个 ...

  4. SQL on Hadoop中用到的主要技术——MPP vs Runtime Framework

    转载声明 本文转载自盘点SQL on Hadoop中用到的主要技术,个人觉得该文章对于诸如Impala这样的MPP架构的SQL引擎和Runtime Framework架构的Hive/Spark SQL ...

  5. dubbo Filter

    官方说明: 调用拦截扩展 扩展说明 服务提供方和服务消费方调用过程拦截,Dubbo 本身的大多功能均基于此扩展点实现,每次远程方法执行,该拦截都会被执行,请注意对性能的影响. 约定: 用户自定义 fi ...

  6. 动态引用外部的Javascript脚本文件[转]

    你可以参考下面方法,进行动态为网页引用外部的Javascript脚本文件.代码写在Page_Init方法内. VB.NET: 下图是运行时,查看HTML的源代码: C#:

  7. Anaconda+django写出第一个web app(三)

    前面我们已经建立了模型Tutorial,也已经可以用Navicat Premium打开数据看查看数据,接下来我们通过建立admin账户来上传数据. 在命令行执行如下命令来创建用户: python ma ...

  8. HDU 3790 最短路径问题 (最短路)

    题目链接 Problem Description 给你n个点,m条无向边,每条边都有长度d和花费p,给你起点s终点t,要求输出起点到终点的最短距离及其花费,如果最短距离有多条路线,则输出花费最少的. ...

  9. Django-数据库增查

    1/ python manage.py shell ---------一般用于调试操作 2/ 建表--定义类 #产品表 class ProductModel(models.Model): #通过类属性 ...

  10. [转]caffe中solver.prototxt参数说明

    https://www.cnblogs.com/denny402/p/5074049.html solver算是caffe的核心的核心,它协调着整个模型的运作.caffe程序运行必带的一个参数就是so ...