原创投稿 | 常用软件
您的位置:网站首页 > 源码分享 > PHP程序 > 正文

用PHP读取和编写XMLDOMPHP技巧

文章作者:三亚上门维修电脑 发布日期:2012/2/13 8:31:01
  有许多技术可用于用 php 读取和编写 xml。本文提供了三种方法读取 xml:使用 dom 库、使用 sax 解析器和使用正则表达式。还介绍了使用 dom 和 php 文本模板编写 xml。

  用 php 读取和编写可扩展标记语言(xml)看起来可能有点恐怖。实际上,xml 和它的所有相关技术可能是恐怖的,但是用 php 读取和编写 xml 不一定是项恐怖的任务。首先,需要学习一点关于 xml 的知识 —— 它是什么,用它做什么。然后,需要学习如何用 php 读取和编写 xml,而有许多种方式可以做这件事。

  本文提供了 xml 的简短入门,然后解释如何用 php 读取和编写 xml。

  什么是 xml?

  xml 是一种数据存储格式。它没有定义保存什么数据,也没有定义数据的格式。xml 只是定义了标记和这些标记的属性。格式良好的 xml 标记看起来像这样:

<name>jack herrington</name>

  这个 <name> 标记包含一些文本:jack herrington。

  不包含文本的 xml 标记看起来像这样:

<powerup />

  用 xml 对某件事进行编写的方式不止一种。例如,这个标记形成的输出与前一个标记相同:

<powerup></powerup>

  也可以向 xml 标记添加属性。例如,这个 <name> 标记包含 first 和 last 属性:

<name first="jack" last="herrington" />

  也可以用 xml 对特殊字符进行编码。例如,& 符号可以像这样编码:

  &

  包含标记和属性的 xml 文件如果像示例一样格式化,就是格式良好的,这意味着标记是对称的,字符的编码正确。清单 1 是一份格式良好的 xml 的示例。

  清单 1. xml 图书列表示例

   <books>   <book>   <author>jack herrington</author>   <title>php hacks</title>   <publisher>o'reilly</publisher>   </book>   <book>   <author>jack herrington</author>   <title>podcasting hacks</title>   <publisher>o'reilly</publisher>   </book>   </books> 

  清单 1 中的 xml 包含一个图书列表。父标记 <books> 包含一组 <book> 标记,每个 <book> 标记又包含 <author>、<title> 和 <publisher> 标记。

  当 xml 文档的标记结构和内容得到外部模式文件的验证后,xml 文档就是正确的。模式文件可以用不同的格式指定。对于本文来说,所需要的只是格式良好的 xml。

  如果觉得 xml 看起来很像超文本标记语言(html),那么就对了。xml 和 html 都是基于标记的语言,它们有许多相似之处。但是,要着重指出的是:虽然 xml 文档可能是格式良好的 html,但不是所有的 html 文档都是格式良好的 xml。换行标记(br)是 xml 和 html 之间区别的一个好例子。这个换行标记是格式良好的 html,但不是格式良好的 xml:

<p>this is a paragraph<br>
with a line break</p>

  这个换行标记是格式良好的 xml 和 html:

<p>this is a paragraph<br />
with a line break</p>

  如果要把 html 编写成同样是格式良好的 xml,请遵循 w3c 委员会的可扩展超文本标记语言(xhtml)标准(参见 参考资料)。所有现代的浏览器都能呈现 xhtml。而且,还可以用 xml 工具读取 xhtml 并找出文档中的数据,这比解析 html 容易得多。

  使用 dom 库读取 xml

  读取格式良好的 xml 文件最容易的方式是使用编译成某些 php 安装的文档对象模型 (dom)库。dom 库把整个 xml 文档读入内存,并用节点树表示它,如图 1 所示。

  图 1. 图书 xml 的 xml dom 树
图书 xml 的 xml dom 树

  树顶部的 books 节点有两个 book 子标记。在每本书中,有 author、publisher 和 title 几个节点。author、publisher 和 title 节点分别有包含文本的文本子节点。

  读取图书 xml 文件并用 dom 显示内容的代码如清单 2 所示。

  清单 2. 用 dom 读取图书 xml

   <?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";   }   ?>   


  脚本首先创建一个 new domdocument 对象,用 load 方法把图书 xml 装入这个对象。之后,脚本用 getelementsbyname 方法得到指定名称下的所有元素的列表。

  在 book 节点的循环中,脚本用 getelementsbyname 方法获得 author、publisher 和 title 标记的 nodevalue。nodevalue 是节点中的文本。脚本然后显示这些值。

  可以在命令行上像这样运行 php 脚本:

% php e1.php
php hacks - jack herrington - o'reilly
podcasting hacks - jack herrington - o'reilly
%

  可以看到,每个图书块输出一行。这是一个良好的开始。但是,如果不能访问 xml dom 库该怎么办?

  用 sax 解析器读取 xml

  读取 xml 的另一种方法是使用 xml simple api(sax)解析器。php 的大多数安装都包含 sax 解析器。sax 解析器运行在回调模型上。每次打开或关闭一个标记时,或者每次解析器看到文本时,就用节点或文本的信息回调用户定义的函数。

  sax 解析器的优点是,它是真正轻量级的。解析器不会在内存中长期保持内容,所以可以用于非常巨大的文件。缺点是编写 sax 解析器回调是件非常麻烦的事。清单 3 显示了使用 sax 读取图书 xml 文件并显示内容的代码。

  清单 3. 用 sax 解析器读取图书 xml

   <?php   $g_books = array();   $g_elem = null;      function startelement( $parser, $name, $attrs )    {   global $g_books, $g_elem;   if ( $name == 'book' ) $g_books []= array();   $g_elem = $name;   }      function endelement( $parser, $name )    {   global $g_elem;   $g_elem = null;   }      function textdata( $parser, $text )   {   global $g_books, $g_elem;   if ( $g_elem == 'author' ||   $g_elem == 'publisher' ||   $g_elem == 'title' )   {   $g_books[ count( $g_books ) - 1 ][ $g_elem ] = $text;   }   }      $parser = xml_parser_create();      xml_set_element_handler( $parser, "startelement", "endelement" );   xml_set_character_data_handler( $parser, "textdata" );      $f = fopen( 'books.xml', 'r' );      while( $data = fread( $f, 4096 ) )   {   xml_parse( $parser, $data );   }      xml_parser_free( $parser );      foreach( $g_books as $book )   {   echo $book['title']." - ".$book['author']." - ";   echo $book['publisher']."\n";   }   ?>   

  脚本首先设置 g_books 数组,它在内存中容纳所有图书和图书信息,g_elem 变量保存脚本目前正在处理的标记的名称。然后脚本定义回调函数。在这个示例中,回调函数是 startelement、endelement 和 textdata。在打开和关闭标记的时候,分别调用 startelement 和 endelement 函数。在开始和结束标记之间的文本上面,调用 textdata。

  在这个示例中,startelement 标记查找 book 标记,在 book 数组中开始一个新元素。然后,textdata 函数查看当前元素,看它是不是 publisher、title 或 author 标记。如果是,函数就把当前文本放入当前图书。

  为了让解析继续,脚本用 xml_parser_create 函数创建解析器。然后,设置回调句柄。之后,脚本读取文件并把文件的大块内容发送到解析器。在文件读取之后,xml_parser_free 函数删除解析器。脚本的末尾输出 g_books 数组的内容。

  可以看到,这比编写 dom 的同样功能要困难得多。如果没有 dom 库也没有 sax 库该怎么办?还有替代方案么?

  用正则表达式解析 xml

  可以肯定,即使提到这个方法,有些工程师也会批评我,但是确实可以用正则表达式解析 xml。清单 4 显示了使用 preg_ 函数读取图书文件的示例。

  清单 4. 用正则表达式读取 xml
   <?php   $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" );   }   ?> 

  请注意这个代码有多短。开始时,它把文件读进一个大的字符串。然后用一个 regex 函数读取每个图书项目。最后用 foreach 循环,在每个图书块间循环,并提取出 author、title 和 publisher。

  那么,缺陷在哪呢?使用正则表达式代码读取 xml 的问题是,它并没先进行检查,确保 xml 的格式良好。这意味着在读取之前,无法知道 xml 是否格式良好。而且,有些格式正确的 xml 可能与正则表达式不匹配,所以日后必须修改它们。

  我从不建议使用正则表达式读取 xml,但是有时它是兼容性最好的方式,因为正则表达式函数总是可用的。不要用正则表达式读取直接来自用户的 xml,因为无法控制这类 xml 的格式或结构。应当一直用 dom 库或 sax 解析器读取来自用户的 xml。

  用 dom 编写 xml

  读取 xml 只是公式的一部分。该怎样编写 xml 呢?编写 xml 最好的方式就是用 dom。清单 5 显示了 dom 构建图书 xml 文件的方式。

   清单 5. 用 dom 编写图书 xml

   <?php   $books = array();   $books [] = array(   'title' => 'php hacks',   'author' => 'jack herrington',   'publisher' => "o'reilly"   );   $books [] = array(   'title' => 'podcasting hacks',   'author' => 'jack herrington',   'publisher' => "o'reilly"   );      $doc = new domdocument();   $doc->formatoutput = true;      $r = $doc->createelement( "books" );   $doc->appendchild( $r );      foreach( $books as $book )   {   $b = $doc->createelement( "book" );      $author = $doc->createelement( "author" );   $author->appendchild(   $doc->createtextnode( $book['author'] )   );   $b->appendchild( $author );      $title = $doc->createelement( "title" );   $title->appendchild(   $doc->createtextnode( $book['title'] )   );   $b->appendchild( $title );      $publisher = $doc->createelement( "publisher" );   $publisher->appendchild(   $doc->createtextnode( $book['publisher'] )   );   $b->appendchild( $publisher );      $r->appendchild( $b );   }      echo $doc->savexml();   ?> 

  在脚本的顶部,用一些示例图书装入了 books 数组。这个数据可以来自用户也可以来自数据库。

  示例图书装入之后,脚本创建一个 new domdocument,并把根节点 books 添加到它。然后脚本为每本书的 author、title 和 publisher 创建节点,并为每个节点添加文本节点。每个 book 节点的最后一步是重新把它添加到根节点 books。

  脚本的末尾用 savexml 方法把 xml 输出到控制台。(也可以用 save 方法创建一个 xml 文件。)脚本的输出如清单 6 所示。

清单 6. dom 构建脚本的输出
   % php e4.php    <?xml version="1.0"?>   <books>   <book>   <author>jack herrington</author>   <title>php hacks</title>   <publisher>o'reilly</publisher>   </book>   <book>   <author>jack herrington</author>   <title>podcasting hacks</title>   <publisher>o'reilly</publisher>   </book>   </books>   % 

  使用 dom 的真正价值在于它创建的 xml 总是格式正确的。但是如果不能用 dom 创建 xml 时该怎么办?

  用 php 编写 xml

  如果 dom 不可用,可以用 php 的文本模板编写 xml。清单 7 显示了 php 如何构建图书 xml 文件。

清单 7. 用 php 编写图书 xml
   <?php   $books = array();   $books [] = array(   'title' => 'php hacks',   'author' => 'jack herrington',   'publisher' => "o'reilly"   );   $books [] = array(   'title' => 'podcasting hacks',   'author' => 'jack herrington',   'publisher' => "o'reilly"   );   ?>   <books>   <?php      foreach( $books as $book )   {   ?>   <book>   <title><?php echo( $book['title'] ); ?></title>   <author><?php echo( $book['author'] ); ?>   </author>   <publisher><?php echo( $book['publisher'] ); ?>   </publisher>   </book>   <?php   }   ?>   </books> 

  脚本的顶部与 dom 脚本类似。脚本的底部打开 books 标记,然后在每个图书中迭代,创建 book 标记和所有的内部 title、author 和 publisher 标记。

  这种方法的问题是对实体进行编码。为了确保实体编码正确,必须在每个项目上调用 htmlentities 函数,如清单 8 所示。

清单 8. 使用 htmlentities 函数对实体编码
    <books>   <?php      foreach( $books as $book )   {   $title = htmlentities( $book['title'], ent_quotes );   $author = htmlentities( $book['author'], ent_quotes );   $publisher = htmlentities( $book['publisher'], ent_quotes );   ?>   <book>   <title><?php echo( $title ); ?></title>   <author><?php echo( $author ); ?> </author>   <publisher><?php echo( $publisher ); ?>   </publisher>   </book>   <?php   }   ?>   </books> 

  这就是用基本的 php 编写 xml 的烦人之处。您以为自己创建了完美的 xml,但是在试图使用数据的时候,马上就会发现某些元素的编码不正确。

  结束语

  xml 周围总有许多夸大之处和混淆之处。但是,并不像您想像的那么难 —— 特别是在 php 这样优秀的语言中。在理解并正确地实现了 xml 之后,就会发现有许多强大的工具可以使用。xpath 和 xslt 就是这样两个值得研究的工具。

注意:联系我时,请一定说明是从【S】看到的信息,谢谢。

编辑:
联系电话:
联系 QQ:
打电话给我、或者加QQ好友时,请一定说明来自(三亚上门维修电脑)谢谢您!
三亚上门维修电脑