php读取xml文件的三种实现方法

回复 已回复1 星标
更多
«
php读取xml文件的三种实现方法
»
-
-

​ 

文章介绍了三种方式来读取xml文件分别是 DOMDocument,正则解析xml,parser函数来读取xml数据,这些方法都是可行的,但第一种和最后一种要好一些。

DOMDocument»

$doc = new DOMDocument();

$doc->load( 'books.xml' );

$books = $doc->getElementsByTagName( "book" );

foreach( $books as $book )

{

$authors = $book->getElementsByTagName( "author" );

$author = $authors->item(0)->nodeValue;

$publishers = $book->getElementsByTagName( "publisher" );

$publisher = $publishers->item(0)->nodeValue;

$titles = $book->getElementsByTagName( "title" );

$title = $titles->item(0)->nodeValue;

echo "$title - $author - $publisher/n";

}

正则解析»

$xml = "";

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

while( $data = fread( $f, 4096 ) ) { $xml .= $data; }

fclose( $f );

preg_match_all( "//<book/>(.*?)/<//book/>/s",

$xml, $bookblocks );

foreach( $bookblocks[1] as $block )

{

preg_match_all( "//<author/>(.*?)/<//author/>/",

$block, $author );

preg_match_all( "//<title/>(.*?)/<//title/>/",

$block, $title );

preg_match_all( "//<publisher/>(.*?)/<//publisher/>/",

$block, $publisher );

echo( $title[1][0]." - ".$author[1][0]." - ".

$publisher[1][0]."/n" );

}

parser函数»

$parser = xml_parser_create(); //创建一个parser编辑器

//设立标签触发时的相应函数 这里分别为startElement和endElenment

xml_set_element_handler($parser, "startElement", "endElement");

xml_set_character_data_handler($parser, "characterData");//设立数据读取时的相应函数

$xml_file="1.xml";//指定所要读取的xml文件,可以是url

$filehandler = fopen($xml_file, "r");//打开文件

//每次取出4096个字节进行处理

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

xml_parse($parser, $data, feof($filehandler));

}

fclose($filehandler);

xml_parser_free($parser);//关闭和释放parser解析器

$name=false;

$position=false;

function startElement($parser_instance, $element_name, $attrs)//起始标签事件的函数

{

global $name,$position;

if($element_name=="NAME"){

$name=true;

$position=false;

echo "名字:";

}

if($element_name=="POSITION"){

$name=false;

$position=true;

echo "职位:";

}

}

//读取数据时的函数

function characterData($parser_instance, $xml_data)

{

global $name,$position;

if($position)

echo $xml_data."<br>";

if($name)

echo $xml_data."<br>";

}

//结束标签事件的函数

function endElement($parser_instance, $element_name)

{

global $name,$position;

$name=false;

$position=false;

}

2015-05-05 12:35:44更新过

正序阅读 1# 2015-05-06 21:44

 

新窗口打开 关闭