自从PHP 5.0以来,PHP能与XML交互的可用选项显著地增加。而PHP版本4所能提供的是不稳定的而且是非w3c兼容的DOM XML扩展。
下面,我将集中讨论PHP 5所提供给我们的三个允许我们与XML交互的方法:DOM,简单XML和XPath。在可能之处,我将建议最适合于每种方法的条件和数据。所有的示例代码将使用XML数据源来描述一个库及其中包含的书。
<xml version="1.0"?>
<library>
<categories>
<category cid="1">Web Development</category>
<category cid="2">Database Programming</category>
<category cid="3">PHP</category>
<category cid="4">Java</category>
</categories>
<books>
<book>
<title>Apache 2</title>
<author>Peter Wainwright</author>
<publisher>Wrox</publisher>
<category>1</category>
</book>
<book>
<title>Advanced PHP Programming</title>
<author>George Schlossnagle</author>
<publisher>Developer Library</publisher>
<category>1</category>
<category>3</category>
</book>
<book>
<title>Visual FoxPro 6 - Programmers Guide</title>
<author>Eric Stroo</author>
<publisher>Microsoft Press</publisher>
<category>2</category>
</book>
<book>
<title>Mastering Java 2</title>
<author>John Zukowski</author>
<publisher>Sybex</publisher>
<category>4</category>
</book>
</books>
</library>