成都网站建设设计

将想法与焦点和您一起共享

如何正确运用PHPXMLReader解析XML文档

我们在运用PHP语言进行实际编程中,经常会遇到需要对XML文档进行解析的需求。在PHP语言中提供了许多函数可以满足这一需求的实现。。其中PHP XMLReader循序地浏览过xml档案的节点,可以想像成游标走过整份文件的节点,并抓取需要的内容。#t#

PHP XMLReader的代码示例如下:

  1. < ?PHP
  2. header("Content-type:text/html;
     Charset=utf-8");
  3. $url = "http://www.google.com/
    ig/api?weather=shenzhen";
  4. // 加载XML内容
  5. $xml = new XMLReader();
  6. $xml->open($url);
  7. $condition = '';
  8. $temp_c = '';
  9. while ($xml->read()) {
  10. // echo $xml->name, "==>", 
    $xml->depth, "
    ";
  11. if (!empty($condition) 
    && !empty($temp_c)) {
  12. break;
  13. }
  14. if ($xml->name == 'condition' 
    && empty($condition)) { 
  15. // 取***个condition
  16. $condition = $xml->getAttribute('data');
  17. }
  18. if ($xml->name == 'temp_c' &&
     empty($temp_c)) { 
  19. // 取***个temp_c
  20. $temp_c = $xml->getAttribute('data');
  21. }
  22. $xml->read();
  23. }
  24. $xml->close();
  25. echo '天气:', $condition, '< br />';
  26. echo '温度:', $temp_c, '< br />'; 

我们只是需要运用PHP XMLReader取***个condition和***个temp_c,于是遍历所有的节点,将遇到的***个condition和***个temp_c写入变量,***输出。


文章名称:如何正确运用PHPXMLReader解析XML文档
网页链接:http://chengdu.cdxwcx.cn/article/codieoe.html