Posted By

onefastsnail on 11/04/10


Tagged


Versions (?)

first use of classes, xml parse


 / Published in: PHP
 

  1. <?php
  2. //alternative solution to this method was to use functions with globals variables!
  3.  
  4. //define the class reference
  5. class rss_parser {
  6.  
  7. //decare variables to be used inside class
  8. var $insideitem = false;
  9. var $tag = "";
  10. var $title = "";
  11. var $description = "";
  12. var $link = "";
  13. var $tags = "";
  14.  
  15.  
  16. //functions to make our class do something!
  17. function start_tag($parser, $tagName, $attrs) {
  18. if ($this->insideitem) {
  19. $this->tag = $tagName;
  20. } elseif ($tagName == "DATACONTENT") {
  21. $this->insideitem = true;
  22. }
  23. $this->tags .= "<br />".$tagName;
  24. }
  25.  
  26. function end_tag($parser, $tagName) {
  27. if ($tagName == "DATACONTENT") {
  28. //output a formatted string with placeholders!
  29. printf("<h1>%s</h1>", htmlspecialchars(trim($this->title)));
  30. echo ($this->description);
  31.  
  32. //empty vars
  33. $this->title = "";
  34. $this->description = "";
  35. $this->link = "";
  36. $this->insideitem = false;
  37. }
  38. }
  39.  
  40. function tag_data($parser, $data) {
  41. if ($this->insideitem) {
  42. switch ($this->tag) {
  43. case "HL1":
  44. $this->title .= $data;
  45. break;
  46. case "P":
  47. $this->description .= "<p>".$data."</p>";
  48. break;
  49. case "A":
  50. $this->description .= "<a href=''>".$data."</a>";
  51. break;
  52. }
  53. }
  54. }
  55. }
  56.  
  57. //create xml parser
  58. $xml_parser = xml_parser_create();
  59.  
  60. //create the class object
  61. $rss_parser = new rss_parser();
  62.  
  63. //This function allows to use parser inside object
  64. xml_set_object($xml_parser, &$rss_parser);
  65.  
  66. xml_set_element_handler($xml_parser, "start_tag", "end_tag");
  67. xml_set_character_data_handler($xml_parser, "tag_data");
  68.  
  69. //open xml file
  70. $fp = fopen("news_sample.xml","r") or die("Error reading XML data.");
  71.  
  72. //read 4kb of the file at a time
  73. while ($data = fread($fp, 32096)){
  74. xml_parse($xml_parser, $data, feof($fp)) or die(sprintf("XML error: %s at line %d",
  75. }
  76.  
  77. //close file and delete parser
  78. fclose($fp);
  79. xml_parser_free($xml_parser);
  80.  
  81. //echo $rss_parser->tags;
  82. ?>

Report this snippet  

You need to login to post a comment.