Heim >php教程 >php手册 >如何正确运用PHP XMLReader解析XML文档

如何正确运用PHP XMLReader解析XML文档

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-13 11:08:471529Durchsuche

我们在运用

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, "br>";  
  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写入变量,最后输出。


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:PHP APC的安装与高级使用Nächster Artikel:详细解读PHP模板的作用