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. Long与long的区别

    Java的数据类型分两种:1.基本类型:long,int,byte,float,double,char2. 对象类型(类): Long,Integer,Byte,Float,Double,Char,S ...

  2. ACF/PACF,残差白噪声的检验问题

    关于自相关.偏自相关: 一.自协方差和自相关系数       p阶自回归AR(p)       自协方差 r(t,s)=E[X(t)-EX(t)][X(s)-EX(s)]       自相关系数ACF ...

  3. mysql查改

    1 MySQL UNION 操作符语法格式: SELECT expression1, expression2, ... expression_n FROM tables [WHERE conditio ...

  4. [老法新用]使用PADDING-TOP:(PERCENTAGE)实现响应式背景图片

    处理响应式布局中背景图片的简单方法是等比例缩放背景图片.我们知道宽度设为百分比的  <img> 元素,其高度会随着宽度的变化自动调整,且其宽高比不变.如果想在背景图片中实现同样的效果,我们 ...

  5. T48566 【zzy】yyy点餐

    T48566 [zzy]yyy点餐 题目描述 yyy去麦肯士吃垃圾食品. 麦肯士有n种单点餐品(汉堡薯条鸡翅之类的).每次选择一种或者以上的餐点,且每种餐点不多于一个的话,可以认为是购买套餐.购买一个 ...

  6. oracle中所有存在不存在的用户都可以使用dba连接到数据库

    oracle中所有存在不存在的用户都可以使用dba连接到数据库及解决方式 以前一直使用conn /as sysdba连接数据库,不明白里面的意思.今天无意中使用其他的用户名密码连接到dba竟然也可以( ...

  7. CF&&CC百套计划1 Codeforces Round #449 B. Ithea Plays With Chtholly

    http://codeforces.com/contest/896/problem/B 题意: 交互题 n张卡片填m个1到c之间的数,1<=n*ceil(c/2)<=m 最后填出一个单调非 ...

  8. 基于 Cocos2d-x-lua 的游戏开发框架 Dorothy 简介

    基于 Cocos2d-x-lua 的游戏开发框架 Dorothy 简介 概述 Dorothy 是一个在 Cocos2d-x-lua 基础上发展起来的分支, 它去掉 Cocos2d-x-lua 那些过多 ...

  9. 2018年9月22日CCPC吉林站参赛总结

    发现思维题是硬伤,代码能力是硬伤,对知识点的理解不深刻是硬伤 接下来要做的就是 1.熟悉每一个知识点,把每一个知识点和实现它的代码联系在一起学习 2.多见题,看看他们是怎么考察这些知识点的,等比赛的时 ...

  10. jQuery合并单元格以及还原重置

    一.合并rowspan jQuery.fn.rowspan = function(colIdx) { return this.each(function(){ var that; $('tr', th ...