Home  >  Article  >  php教程  >  php读取xml的神器

php读取xml的神器

WBOY
WBOYOriginal
2016-06-06 19:44:471134browse

?xml version="1.0 encoding="UTF-8"? humans zhangying name张映/name sex男/sex old28/old /zhangying tank nametank/name sex男/sex old28/old /tank /humans 1)DOMDocument读取xml ?php $doc = new DOMDocument(); $doc-load('person.xml'); //读取xml

张映

28

tank

28

1)DOMDocument读取xml

$doc = new DOMDocument();

$doc->load('person.xml'); //读取xml文件

foreach( $humans as $human )

{

$name = $names->item(0)->nodeValue; //取得node中的值,如

$sexs = $human->getElementsByTagName_r( "sex" );

$sex = $sexs->item(0)->nodeValue;

$olds = $human->getElementsByTagName_r( "old" );

$old = $olds->item(0)->nodeValue;

echo "$name - $sex - $old\n";

}

?>

2)simplexml读取xml

 

 

$xml_array=simplexml_load_file('person.xml'); //将XML中的数据,读取到数组对象中

foreach($xml_array as $tmp){

echo $tmp->name."-".$tmp->sex."-".$tmp->old."
";

}

?>

3)用php正则表达式来记取数据 / http://www.pprar.com  

$xml = "";

$f = fopen('person.xml', 'r');

while( $data = fread( $f, 4096 ) ) {

$xml .= $data;

}

fclose( $f );

// 上面读取数据

 

foreach( $humans[1] as $k=>$human )

{

preg_match_all( "/\(.*?)\/", $human, $name ); //匹配出名字

preg_match_all( "/\(.*?)\/", $human, $sex ); //匹配出性别

preg_match_all( "/\(.*?)\/", $human, $old ); //匹配出年龄

}

 

foreach($name[1] as $key=>$val){

echo $val." - ".$sex[$key][1]." - ".$old[$key][1]."
" ;

}

?>

 

 

4)xmlreader来读取xml数据

 

 

$reader = new XMLReader();

$reader->open('person.xml'); //读取xml数据

$i=1;

while ($reader->read()) { //是否读取

if ($reader->nodeType == XMLReader::TEXT) { //判断node类型

if($i%3){

echo $reader->value; //取得node的值

}else{

echo $reader->value."
" ;

}

$i++;

}

}

?>

 

三,小结

 

xmlreader的设计重点是为了读data里面的name sex old的值,而读取的内容就比较麻烦了。他相当于jquery中attr(”);这个东西。

大家如果有好的办法读取xml,可以加上

Statement:
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