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

作者:袖梨 2022-06-24
代码如下 复制代码

php
$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/>/s",
$xml, $bookblocks );

foreach( $bookblocks[1] as $block )
{
preg_match_all( "//(.*?)//author/>/",
$block, $author );
preg_match_all( "//(.*?)//title/>/",
$block, $title );
preg_match_all( "//(.*?)//publisher/>/",
$block, $publisher );
echo( $title[1][0]." - ".$author[1][0]." - ".
$publisher[1][0]."/n" );
}
?>


books.xml文件如下

代码如下 复制代码


Jack Herrington
PHP Hacks
O'Reilly


Jack Herrington
Podcasting Hacks
O'Reilly


下面就给大家举一个小小的例子用parser函数来读取xml数据:

代码如下 复制代码

$parser = xml_parser_create(); //创建一个parser编辑器
xml_set_element_handler($parser, "startElement", "endElement");//设立标签触发时的相应函数 这里分别为startElement和endElenment
xml_set_character_data_handler($parser, "characterData");//设立数据读取时的相应函数
$xml_file="1.xml";//指定所要读取的xml文件,可以是url
$filehandler = fopen($xml_file, "r");//打开文件


while ($data = fread($filehandler, 4096))
{
xml_parse($parser, $data, feof($filehandler));
}//每次取出4096个字节进行处理

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."
";
if($name)
echo $xml_data."
";
}

function endElement($parser_instance, $element_name) //结束标签事件的函数
{
global $name,$position;
$name=false;
$position=false;
}

?>

xml文件代码如下:

代码如下 复制代码




张三
经理



李四
助理

parser是php内置的一个用来处理xml的解析器,它的工作由三个事件组成:起始标签、 读取数据、结束标签。

也就是说在对xml进行处理的时候每当遇到起始标签、数据和结束标签的时候函数会做相应的动作来完成对xml数据的转换。

相关文章

精彩推荐