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. Chapter 4(栈与队列)

    1.栈的顺序存储结构 //*********************************stack_array.h************************************ #ifn ...

  2. linux操作系统位数

    方法1:getconf LONG_BIT 查看 如下例子所示: 32位Linux系统显示32, 64位Linux系统显示64.最简单.快捷的方法. [root@DB-Server ~]# getcon ...

  3. Python高手之路【七】python基础之模块

    本节大纲 模块介绍 time &datetime模块 random os sys shutil json & picle shelve xml处理 yaml处理 configparse ...

  4. Java基础-面向对象第三大特性之多态(polymorphism )

    Java基础-面向对象第三大特性之多态(polymorphism) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.多态概述 多态是继封装,继承之后,面向对象的第三大特性,多态的 ...

  5. git爬坑不完全指北(二):failed to push some refs to ‘XXX’的解决方案

    报错分析        从字面理解,这个报错的意思就是说远程仓库里有一个改动是本地仓库里没有的,所以在push前要先把远程仓库上的改动pull或者fetch到本地仓库.然后再执行push的操作,把本地 ...

  6. bzoj千题计划173:bzoj1257: [CQOI2007]余数之和sum

    http://www.lydsy.com/JudgeOnline/problem.php?id=1257 k%i=k-int(k/i)*i 除法分块,对于相同的k/i用等差序列求和来做 #includ ...

  7. SQL语句(二十一)—— 触发器(DML触发器)

    触发器 一 .触发器概述(特殊的存储过程) 定义: 在修改指定表值的数据时执行的 存储过程. 不同的是 : 执行存储过程要使用EXEC语句来调用,而触发器的执行不需要使用EXEC语句来调用. 作用: ...

  8. git 第一次关联远程仓库

    1.首先需要先git pull origin master 2.然后合并两个无关的仓库 git pull origin master --allow-unrelated-histories

  9. Redis实战(一)CentOS 7上搭建redis-3.0.2

    1.安装redis wget http://download.redis.io/releases/redis-3.0.2.tar.gz tar zxvf redis-3.0.2.tar.gz cd   ...

  10. 可供选择CSS框架

    在这里你有一个很酷的框架,收集创建的CSS布局. 如果你不喜欢框架,宁愿使用自己的手写代码以促进自己的发展,请跳过本篇文章. 我想有一个建设性的意见,那就是有选择的使用其优点避开其缺点. 就个人而言, ...