我们在运用PHP语言进行实际编程中,经常会遇到需要对XML文档进行解析的需求。在PHP语言中提供了许多函数可以满足这一需求的实现。。其中PHP XMLReader循序地浏览过xml档案的节点,可以想像成游标走过整份文件的节点,并抓取需要的内容。
PHP XMLReader的代码示例如下:
- < ?PHP
- header("Content-type:text/html;
Charset=utf-8"); - $url = "http://www.google.com/
ig/api?weather=shenzhen"; - // 加载XML内容
- $xml = new XMLReader();
- $xml->open($url);
- $condition = '';
- $temp_c = '';
- while ($xml->read()) {
- // echo $xml->name, "==>",
$xml->depth, "<br>"; - if (!empty($condition)
&& !empty($temp_c)) { - break;
- }
- if ($xml->name == 'condition'
&& empty($condition)) { - // 取第一个condition
- $condition = $xml->getAttribute('data');
- }
- if ($xml->name == 'temp_c' &&
empty($temp_c)) { - // 取第一个temp_c
- $temp_c = $xml->getAttribute('data');
- }
- $xml->read();
- }
- $xml->close();
- echo '天气:', $condition, '< br />';
- echo '温度:', $temp_c, '< br />';
我们只是需要运用PHP XMLReader取第一个condition和第一个temp_c,于是遍历所有的节点,将遇到的第一个condition和第一个temp_c写入变量,最后输出。
-------------------------------------
[代码] [PHP]代码
03 | <?xml version= "1.0 encoding=" UTF-8"?> |
19 | $reader = new XMLReader(); |
20 | $reader ->open( 'person.xml' ); |
22 | while ( $reader ->read()) { |
23 | if ( $reader ->nodeType == XMLReader::TEXT) { |
27 | echo $reader ->value. "<br>" ; |
------------------------------------------------------
libxml2 contains much more useful method readString() that will read and return whole text content of element. You can call it after receiving start tag (XMLReader::ELEMENT). You can use this PHP code to emulate this method until PHP will directly call underlying libxml2 implementation.
<?php
class
XMLReader2
extends
XMLReader
{
function
readString
()
{
$depth
=
1
;
$text
=
""
;
while (
$this
->
read
() &&
$depth
!=
0
)
{
if (
in_array
(
$this
->
nodeType
, array(
XMLReader
::
TEXT
,
XMLReader
::
CDATA
,
XMLReader
::
WHITESPACE
,
XMLReader
::
SIGNIFICANT_WHITESPACE
)))
$text
.=
$this
->
value
;
if (
$this
->
nodeType
==
XMLReader
::
ELEMENT
)
$depth
++;
if (
$this
->
nodeType
==
XMLReader
::
END_ELEMENT
)
$depth
--;
}
return
$text
;
}
}
?>
Just use XMLReader2 instead of XMLReader.