Home Backend Development PHP Tutorial PHP class for reading xml

PHP class for reading xml

Jul 25, 2016 am 09:04 AM

  1. #------------------------------------------

  2. #
  3. # XML Library, by Keith Devens, version 1.2b
  4. # http://keithdevens.com/software/phpxml
  5. #
  6. # This code is Open Source, released under terms similar to the Artistic License.
  7. # Read the license at http://keithdevens.com/software/license
  8. #
  9. #------------------------------------------
  10. # XML_unserialize: takes raw XML as a parameter (a string)
  11. # and returns an equivalent PHP data structure
  12. #------------------------------------------
  13. function & XML_unserialize(&$xml){
  14. $xml_parser = &new XML();
  15. $data = &$xml_parser->parse($xml);
  16. $xml_parser->destruct();
  17. return $data;
  18. }
  19. -----------------------#####
  20. # XML_serialize: serializes any PHP data structure into XML
  21. # Takes one parameter: the data to serialize. Must be an array.
  22. -----------------------#
  23. function & XML_serialize(&$data, $level = 0, $prior_key = NULL){
  24. if($level == 0){ ob_start(); echo '',"n"; }
  25. while(list($key, $value) = each($data))
  26. if(!strpos($key, ' attr')) #if it's not an attribute
  27. #we don't treat attributes by themselves, so for an empty element
  28. # that has attributes you still need to set the element to NULL

  29. if(is_array($value) and array_key_exists(0, $value)){

  30. XML_serialize($value, $level, $key);
  31. }else{
  32. $tag = $prior_key ? $prior_key : $key;
  33. echo str_repeat("t", $level),'<',$tag;
  34. if(array_key_exists("$key attr", $data)){ #if there's an attribute for this element
  35. while(list($attr_name, $attr_value) = each($data["$key attr"]))
  36. echo ' ',$attr_name,'="',htmlspecialchars($attr_value),'"';
  37. reset($data["$key attr"]);
  38. }

  39. if(is_null($value)) echo " />n";

  40. elseif(!is_array($value)) echo '>',htmlspecialchars($value),"n";
  41. else echo ">n",XML_serialize($value, $level+1),str_repeat("t", $level),"n";
  42. }
  43. reset($data);
  44. if($level == 0){ $str = &ob_get_contents(); ob_end_clean(); return $str; }
  45. }
  46. #-----------------------#
  47. # XML class: utility class to be used with PHP's XML handling functions
  48. #-----------------------#
  49. class XML{
  50. var $parser; #a reference to the XML parser
  51. var $document; #the entire XML structure built up so far
  52. var $parent; #a pointer to the current parent - the parent will be an array
  53. var $stack; #a stack of the most recent parent at each nesting level
  54. var $last_opened_tag; #keeps track of the last tag opened.

  55. function XML(){

  56. $this->parser = &xml_parser_create();
  57. xml_parser_set_option(&$this->parser, XML_OPTION_CASE_FOLDING, false);
  58. xml_set_object(&$this->parser, &$this);
  59. xml_set_element_handler(&$this->parser, 'open','close');
  60. xml_set_character_data_handler(&$this->parser, 'data');
  61. }
  62. function destruct(){ xml_parser_free(&$this->parser); }
  63. function & parse(&$data){
  64. $this->document = array();
  65. $this->stack = array();
  66. $this->parent = &$this->document;
  67. return xml_parse(&$this->parser, &$data, true) ? $this->document : NULL;
  68. }
  69. function open(&$parser, $tag, $attributes){
  70. $this->data = ''; #stores temporary cdata
  71. $this->last_opened_tag = $tag;
  72. if(is_array($this->parent) and array_key_exists($tag,$this->parent)){ #if you've seen this tag before
  73. if(is_array($this->parent[$tag]) and array_key_exists(0,$this->parent[$tag])){ #if the keys are numeric
  74. #this is the third or later instance of $tag we've come across
  75. $key = count_numeric_items($this->parent[$tag]);
  76. }else{
  77. #this is the second instance of $tag that we've seen. shift around
  78. if(array_key_exists("$tag attr",$this->parent)){
  79. $arr = array('0 attr'=>&$this->parent["$tag attr"], &$this->parent[$tag]);
  80. unset($this->parent["$tag attr"]);
  81. }else{
  82. $arr = array(&$this->parent[$tag]);
  83. }
  84. $this->parent[$tag] = &$arr;
  85. $key = 1;
  86. }
  87. $this->parent = &$this->parent[$tag];
  88. }else{
  89. $key = $tag;
  90. }
  91. if($attributes) $this->parent["$key attr"] = $attributes;
  92. $this->parent = &$this->parent[$key];
  93. $this->stack[] = &$this->parent;
  94. }
  95. function data(&$parser, $data){
  96. if($this->last_opened_tag != NULL) #you don't need to store whitespace in between tags
  97. $this->data .= $data;
  98. }
  99. function close(&$parser, $tag){
  100. if($this->last_opened_tag == $tag){
  101. $this->parent = $this->data;
  102. $this->last_opened_tag = NULL;
  103. }
  104. array_pop($this->stack);
  105. if($this->stack) $this->parent = &$this->stack[count($this->stack)-1];
  106. }
  107. }
  108. function count_numeric_items(&$array){
  109. return is_array($array) ? count(array_filter(array_keys($array), 'is_numeric')) : 0;
  110. }
  111. ?>

复制代码

Application example, XML source address: http://data.cnaz.com/spread/?tid=7&sid=42845&order=date&flags=desc&num=50 &page=1&hosts=pic.ttiankan.com&code=xml

  1. include('xml.php'); //Reference PHP XML operation class

  2. $page=$_GET['page '];

  3. if(empty($page) || !is_numeric($page)) $page=1;

  4. //Idol star

  5. $ xml = file_get_contents('http://data.cnaz.com/spread/?tid=7&sid=42845&order=date&flags=desc&num=50
  6. &page='.$page.'&hosts=pic.ttiankan.com&code=xml');

  7. //$xml = file_get_contents("php://input"); //Read the input stream from POST
  8. $data=XML_unserialize($xml);
  9. $item=$data['rss']['channel'];

  10. $link = $item['link'];

  11. $description= $item[ 'description'];
  12. $keywords = $item['keywords'];
  13. $totalnum = $item['totalnum'];
  14. $usetime = $item['usetime'];

  15. echo('

    Keywords:'.$keywords.' ');
  16. echo('Total number of records:'.$totalnum.', 50 records per page, total '.$totalpage.' Page, currently page '.$page.'
');

  • $item=$item['item'];

  • ');

  • echo('

  • ');

  • foreach($item as $list)

  • {
  • echo('
  • ');
  • echo('
  • ');
  • echo('
  • ');
  • echo('
  • ');
  • echo('');
  • }

  • echo('

  • ') ;

  • echo('

  • Category Title Link
    '.$list[ 'sort'].' '.$list['title'].' '.$list['link'].'
  • ');
  • if($page>1) echo(' Previous page ');
  • if($page<$totalpage) echo('< a href="b.php?page='.($page+1).'">Next page');
  • echo('
  • ');
  • ?>

  • Copy code

    The editor of Script School recommends for you: Example code for php operation xml Introduction to how to read and write xml files in php Example of using php function to output XML file Example of php using function method to read XML file Several ways to read XML with PHP PHP code for reading XML values Various methods of php operating xml analysis 4 ways to generate xml files with PHP Detailed explanation of simple example of php generating xml An example of adding data to xml using php Learn php to operate XML class DOMDocument with examples



    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25: How To Unlock Everything In MyRise
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

    The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

    12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

    Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

    Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

    Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

    Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

    JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

    Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

    Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

    Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

    The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

    How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

    Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

    See all articles