12.12阅读RSS和Atom Feeds

12.12.1问题
You want to retrieve RSS and Atom feeds and look at the items. This allows you to incorporate newsfeeds from

multiple web sites into your application.

你想要找回RSS和Atom feeds和考虑在这个items. 它允许你合并newsfeeds从多种web sites到你的应用程序

12.12.2解答
Use the MagpieRSS parser. Here’s an example that reads the RSS feed for the php.announce mailing list:

使用这个MagpieRss 剖析器。这里是一个例子阅读Rss feed到这个php.annouce邮件发送清单


?php
require 'rss_fetch.inc';
$feed = 'http://news.php.net/group.php?group=php.announce&format=rss';
$rss = fetch_rss( $feed );
print "<ul>\n";
foreach ($rss->items as $item) {
    print '<li><a href="' . $item['link'] . '">' . $item['title'] . "</a></li>\n";
}
print "</ul>\n";

12.12.3讨论

RSS (RDF Site Summary) is an easy-to-use headline or article syndication format written in XML.[] Many news

web sites, such as the New York Times and the Washington Post, provide RSS feeds that update whenever new

stories are published. Weblogs have also embraced RSS and having an RSS feed for your blog is a standard

feature. The PHP web site also publishes RSS feeds for most PHP mailing lists.
RSS(RDF主要摘要)是一个很容易使用和表达syndication 格式在XML.[]很多的新的web sites 。例如纽约时间和华盛顿时间

。规定RSS feeds 修正无论新的存储内容是pubished,博客同样经常使用RSS和蚩尤一个RSS feed在你的bolg是一个标准的特

质。这个PHP web站点同样订阅RSS feeds在更多的PHP mailing lists


[] RDF stands for Resource Definition Framework. RSS also stands for Rich Site Summary.

Atom is a similar XML syndication format. It extends many of the concepts in RSS, including a way to read and

write Atom data. It also attempts to provide a more well-defined syntax for syndication than RSS, as the RSS

specification doesn’t always clearly enumerate exactly what is or isn’t permissible in a feed.
Atom 是一个相似的XML syndication格式。它延展更多观念到RSS .包括一个办法去阅读和写Atom 数据。它同样尝试规定一

个更多的well-defined语法在syndication比RSS. 当作RSS规范不能明显的列举正确的

Using MagpieRSS, retrieving and parsing RSS and Atom feeds are simple:
使用MagpieRss。找回分解RSS和Atom feeds是简单的


?php
$feed = 'http://news.php.net/group.php?group=php.announce&format=rss';
$rss = fetch_rss($feed);

This example reads in the RSS feed for the php.announce mailing list. The feed is then parsed by fetch_rss( )

and stored internally within $rss.
这个例子阅读在这个RSS feed在这个php.announce mailing list 。这个feed是分解fetch_rss()和存储到$rss内

While this feed is RSS 0.93, there’s no need to specify this to MagpieRSS. Its fetch_rss( ) function detects

the syndication format, including Atom, and formats the document accordingly.
使用这个feed是RSS 0.93 ,它不需要指定这些到MagpieRSS .它的fetch_rss()函数发现这个syndication格式。包括Atom 和

这个格式
Each RSS item is then retrieved as an associative array using the items property:

每个RSS消息重新找回当作一个联合数组使用items 特质

?php
print "<ul>\n";
foreach ($rss->items as $item) {
    print '<li><a href="' . $item['link'] . '">' . $item['title'] . "</a></li>\n";
}
print "</ul>\n";

This foreach loop creates an unordered list of items with the item title linking back to the URL associated

with the complete article, as shown in Figure 12-1. Besides the required title and link fields, an item can

have an optional description field that contains a brief write-up about the item.
这个foreach循环创造一个无序目录消息在这个item字幕背景到联合URL和全部文章。例如在图像12-1.除此之外必须的标题和

链接域。一个item可以有一个可选择的描写 field包含一个主要write-up这个item

Each channel also has an entry with information about the feed, as shown in Figure 12-2. To retrieve that

data, call access the channel attribute:
每个channel同样有一个入口和这个feed的信息。例如在图像12-2,去重新找回那个数据调用访问这个频道的特质

?php
$feed = 'http://news.php.net/group.php?group=php.announce&format=rss';
$rss = fetch_rss($feed);
print "<ul>\n";
foreach ($rss->channel as $key => $value) {
    print "<li>$key: $value</li>\n";
}
print "</ul>\n";

12.11处理编码内容

12.11.1问题
PHP XML extensions use UTF-8, but your data is in a different content encoding.

PHP的XML延展名使用UTF-8。但是你的数据在一个不同的内容编码

12.11.2解答

Use the iconv library to convert it before passing it into an XML extension:

使用这个iconv library去转换它,到一个XML延展名


$utf_8 = iconv('ISO-8859-1', 'UTF-8', $iso_8859_1);

Then convert it back when you are finished:
然后转换它当你完成

12.11.3讨论
Character encoding is a major PHP 5 weakness. Fortunately, Unicode support is the major driver behind PHP 6.

Since PHP 6 is still under development, in the meantime, you can run into problems if you’re trying to use

XML extensions with arbitrary encoded data.

创造编码是PHP5的主要弱点、幸运的是。统一编码支持主驱动器在PHP6.之后。从PHP6之前一直不完善,同时,你可以运行它

的问题如果你尝试去使用XML延展名和任意编码数据

For simplicity, the XML extensions all exclusively use the UTF-8 character encoding. That means they all

expect data in UTF-8 and output all data in UTF-8. If your data is ASCII, then you don’t need to worry, UTF-8

is a superset of ASCII. However, if you’re using other encodings, then you will run into trouble sooner or

later.

对于简单的。这个XML延展名所有专用使用这个UTF-8编码。意思是所有的数据在UTF-8输出数据在UTF-8.如果你的数据是

ASCII, 然后你不需要担心。 UTF-8是扩展集,尽管如果你使用其他编码 然后当你运行故障或者更迟
 
To work around this issue, use the iconv extension to manually encode data back and forth between your

character sets and UTF-8. For example, to convert from ISO-8859-1 to UTF-8:

去运行这个issue。 使用这个图标的延长部分手动编辑数据来回鱼你的字符集和UTF-8。例如转换ISO-8859到UTF-8


$utf_8 = iconv('ISO-8859-1', 'UTF-8', $iso_8859_1);

The iconv function supports two special modifiers for the destination encoding: //TRANSLIT and //IGNORE. The

first option tells iconv that whenever it cannot exactly duplicate a character in the destination encoding,

it should try to approximate it using a series of other characters. The other option makes iconv silently

ignore any unconvertible characters.

这个图标函数支持两个特殊的修正目的文件的编辑://TRANSLIT和//IGNORE。这第一个选项告诉iconv不能正确的复制一个特

性在目的文件编辑,你应该尝试接近它使用一脸产的其他特质。这个其他选项会默默的忽视一些不能转换的特质

For example, the string $geb holds the text Gödel, Escher, Bach. A straight conversion to ASCII produces an

error:

例如。这个字符串$geb保存这个正文 Gödel,Escher, Bach.,一个整齐的变化到ASCII录制一个错误

echo iconv('UTF-8', 'ASCII', $geb);
PHP Notice:  iconv(): Detected an illegal character in input string...


echo iconv('UTF-8', 'ASCII//IGNORE', $geb);

However, the output isn’t nice, because the ö is missing:

尽管。这个输出不是最精密的。因为这个”ö”丢失


Gdel, Escher, Bach

The best solution is to use //trANSLIT:

这个最好的解答办法就是使用//trANSLIT


echo iconv('UTF-8', 'ASCII//TRANSLIT', $geb);

This produces a better-looking string:

它产生更好的字符串

Gdel, Escher, Bach

12.10确认XML文件

12.10.1问题

You want to make sure your XML document abides by a schema, such as XML Schema, RelaxNG, and DTDs.

你想要确认你的XML文件坚持一个计划。例如XML计划。RelaxNG.和DTDs

12.10.2解答

Use the DOM extension
使用这个DOM延展名

With existing DOM objects, call DOMDocument::schemaValidate( ) or DOMDocument::relaxNGValidate( ):

使用现有的DOM对象。调用DOMDocument::schemaVlidate()或者DOMDOcument::relaxNGValidate()


$file = 'address-book.xml';
$schema = 'address-book.xsd';
$ab = new DOMDocument
$ab->load($file);
if ($ab->schemaValidate($schema)) {
    print "$file is valid.\n";
} else {
    print "$file is invalid.\n";
}

If your XML document specifies a DTD at the top, call DOMDocument::validate( ) to validate it against the DTD.

如果你的XML文件指定一个DTD在这个top、调用DOMDocument::validate()去确认它相反的DTD

With XML in a string, call DOMDocument::schemaValidateSource( ) or DOMDocument::relaxNGValidateSource( ):

然后XML在一个字符串。调用ODMDocument::schemaValidateSource()或者DOMDocument::relaxNGValidateSource()


$xml = '<person><firstname>Adam</firstname></person>';
$schema = 'address-book.xsd';
$ab = new DOMDocument
$ab->&gt;load($file);
if ($ab->&gt;schemaValidateSource($schema)) {
    print "XML is valid.\n";
} else {
    print "XML is invalid.\n";
}

12.10.3讨论
Schemas are a way of defining a specification for your XML documents. While the goal is the same, there are multiple

ways to encode a schema, each with a different syntax.

计划是详细定义你的XML文件。当目标是一样的。有多种办法去编辑一个计划,每个不疼痛的语法

Some popular formats are DTDs (Document Type Definitions), XML Schema, and RelaxNG. DTDs have been around longer, but

they are not written in XML and have other issues, so they can be difficult to work with. XML Schema and RelaxNG are

more recent schemas and attempt to solve some of the issues surrounding DTDs.
一些通俗的格式是DTDs(Document Type Definitions)XML Schema 和RelaxNG. DTDs有一个比较久的,但是它不在XML和其他issues.所

以它不同于其他XML

PHP 5 uses the libxml2 library to provide its validation support. Therefore, it lets you validate files against all

three types. It is most flexible when you’re using XML Schema and RelaxNG, but its XML Schema support is incomplete.

You shouldn’t run into issues in most XML Schema documents; however, you may find that libxml2 cannot handle some

complex schemas or schemas that use more esoteric features.

PHP5使用这个libxml2库规定确认支持。因此它设置你的有效文件相反于全部的三个类型。它是大部分灵活的,当你使用XML Schema和

RealxNG,但是它XML Schema支持相反的。你需要运行到最多的XML Schema文件。尽管你可能找到那个libxml2不能处理多数复杂的

schemas或者schemas那个使用更多的深奥的features
Within PHP, the DOM extension supports DTD, XML Schema, and RelaxNG validation, while SimpleXML provides only an XML

Schema validator.

使用PHP.这个DOM延展名支持DTD。 XML Schema 和RealxNG确认。使用简单的规定唯一的一个XML Schema有效的

Validating any file using DOM is a similar process, regardless of the underlying schema format. To validate, call a

validation method on a DOM object (see Example 12-21). It returns true if the file passes. If there’s an error, it

returns false and prints a message to the error log. There is no method for “capturing” the error message

确认一些文件使用DOM是一个相似的处理方法,不管下面的schema格式。有效的调用一个有效的方法在一个DOM对象.它返回真实的文件

。如果是一个错误的。它返回错误然后打印出一个信息到这个错误行。它没有办法处理错误信息


$file = 'address-book.xml';
$schema = 'address-book.xsd';
$ab = new DOMDocument
$ab->load($file);
if ($ab->schemaValidate($schema)) {
    print "$file is valid.\n";
} else {
    print "$file is invalid.\n";
}

If the schema is stored in a string, use DOMDocument::schemaValidateSource( ) instead of schemaValidate( ).

如果这个schema存储在一个字符串。使用DOMDocument::scheemaValidateSource()代替SchemaValidate()

All of the validation methods behave in a similar manner, so you only need to switch the method name in the previous

example to switch to a different validation scheme.
所有的有效方法在某种意义上相似。所以你仅仅需要转换方法命在上一级的菜单例子到一个不同的scheme
Both XML Schema and RelaxNG support validation against files and strings. You can validate a DOM object only against

the DTD defined at the top of the XML document

所有的XML Schema和RllaxNG 支持确认相反的文件和字符串,你可以确认一个DOM对象唯一相反的DTD定义XML文件的顶部

12.9从XSLT Stylesheets 调用PHP函数

12.9.1问题
You want to call PHP functions from within an XSLT stylesheet.

你想要调用PHP函数从一个XSLT stylesheet

12.9.2解答
Invoke the XSLTProcessor::registerPHPFunctions( ) method to enable this functionality
调用XSLTProcessor::registerPHPFunctions()方法到functionlity

$xslt = new XSLTProcessor();
$xslt->registerPHPFunctions();

And use the function( ) or functionString( ) function within your stylesheet:
然后使用这个function()或者functionString()函数和你的风格

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform
    xmlns:php=”http://php.net/xsl
    xsl:extension-element-prefixes=”php”>
<xsl:template match=”/”>
    <xsl:value-of select=”php:function(’strftime’, ‘%c’)” />
</xsl:template>
</xsl:stylesheet>

12.9.3讨论
XSLT parameters are great when you need to communicate from PHP to XSLT. However, they’re not very useful

when you require the reverse. You can’t use parameters to extract information from the stylesheet during the

transformation. Ideally, you could call PHP functions from a stylesheet and pass information back to PHP.

XSLT参数是重要的。当你需要沟通XSLT。他不是非常有用当你命令这个reverse,你不可以使用选出的信息从stylesheet在这

个转换。完美的。你可以调用PHP函数从一个stylesheet和通过信息到PHP

Fortunately, there’s a method that implements this functionality: registerPHPFunctions( ). Here’s how it’s

enabled:

幸运的。这是一个执行这个函数的方法:regiterPHP函数,当它激活

$xslt = new XSLTProcessor();
$xslt->registerPHPFunctions();

This allows you to call any PHP function from your stylesheets. It’s not available by default because it

presents a security risk if you’re processing stylesheets controlled by other people.
它允许你调用一些PHP函数从你的stylesheets。他不是一个可利用的,因为它出现在危险的。如果你处理限制它

Both built-in and user-defined functions work. Inside your stylesheet, you must define a namespace and call

the function( ) or functionString( ) methods, as shown in Example 12-17.

所有的内置和自定义函数工作。代替你的stylesheet。你必须定义一个名字和调用这个函数()或者fanctionString()方法。

例如在例子12-17

<?xml version="1.0" ?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform
    xmlns:php=”http://php.net/xsl
    xsl:extension-element-prefixes=”php”>
<xsl:template match=”/”>
    <xsl:value-of select=”php:function(’strftime’, ‘%c’)” />
</xsl:template>
</xsl:stylesheet>

At the top of the stylesheet, define the namespace for PHP: http://php.net/xsl. This example sets the

namespace prefix to php. Also, set the extension-element-prefixes value to php so XSLT knows these are

functions.

在stylesheet的顶部。定义PHP的域名:http://php.net/xsl.这个例子规定这个前缀是php。设置延展名的元素智到PHP所有

XSLT知道这些函数

To call a PHP function, reference php:function( ). The first parameter is the function name; additional

parameters are the function arguments. In this case, the function name is strftime and the one argument is %

c. This causes strftime to return the current date and time.
去调用一个PHP函数,涉及PHP::function(),这第一个论点是这个函数。另外参数是函数论点,既然这样这个函数名是这个

时间和第一个%c。它导致返回正确的数据和时间
Example 12-18 uses this stylesheet, stored as stylesheet.xsl, to process a single-element XML document
例子12-18使用这个stylesheet。存储在stylesheet,xsl。去存储一个单一的元素XML论点


$dom  = new DOMDocument;
$dom->loadXML('<blank/>');
$xsl  = new DOMDocument
$xsl->load('stylesheet.xsl');
$xslt = new XSLTProcessor();
$xslt->importStylesheet($xsl);
$xslt->registerPHPFunctions();
print $xslt->transformToXML($dom);
Mon Jul 22 19:10:21 2004

This works like standard XSLT processing, but there’s an additional call to registerPHPFunctions( ) to

activate PHP function support.

这个工作就像XSLT的标准。但是它是一个复交的调用registerPHPFunctions()激活PHP函数

You can also return DOM objects. Example 12-19 takes the XML address book and mangles all the email addresses

to turn the hostname portion into three dots. Everything else in the document is left untouched.
你同样可以返回DOM对象。例子12-19调用这个XML地址和所有的email地址去转换这个名字的一部分到three格式。每个其他的

在这个文件是为改变的


function mangle_email($nodes) {
    return preg_replace('/([^@\s]+)@([-a-z0-9]+\.)+[a-z]{2,}/is',
                        ‘$1@…’,
                        $nodes[0]->nodeValue);
}
$dom  = new DOMDocument;
$dom->load(’address-book.xml’);
$xsl  = new DOMDocument
$xsl->load(’stylesheet.xsl’);
$xslt = new XSLTProcessor();
$xslt->importStylesheet($xsl);
$xslt->registerPhpFunctions();
print $xslt->transformToXML($dom);

Inside your stylesheet, create a special template for /address-book/person/email elements, as shown in

Example 12-20.

在你的stylesheet内部,包含一个特殊的模板。对于/address-book/person/email元素。例如在例子12-20

<?xml version="1.0" ?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform
  xmlns:php=”http://php.net/xsl
  xsl:extension-element-prefixes=”php”>
<xsl:template match=”@*|node()”>
  <xsl:copy>
    <xsl:apply-templates select=”@*|node()”/>
  </xsl:copy>
</xsl:template>
<xsl:template match=”/address-book/person/email”>
  <xsl:copy>
    <xsl:value-of select=”php:function(’mangle_email’, node())” />
  </xsl:copy>
</xsl:template>
</xsl:stylesheet>

The first template ensures that the elements aren’t modified, while the second passes the current node to PHP

for mangling. In the second template, the mangle_email( ) function is passed the current node, represented in

XPath as node( ), instead of a string. Be sure not to place the node inside quotation marks, or you’ll pass

the literal text node( ).

这第一个模板确保这个元素不能修改。当这第二个通用正确的网点到PHP。在第二个模板这个mangle_email()函数通过这个正

确的网点。表现在XPath当作node()。代替一个字符串、确认网点在引号内。。或者你通过文字正文
Nodes becomes DOM objects inside PHP and always arrive in an array. In this case, mangle_email( ) knows

there’s always only one object and it’s a DOMText object, so the email address is located in $nodes[0]-

>nodeValue.

网点变成DOM对象代替PHP和总是到达一个数组。既然这样,mangle_email()知道这个总是唯一的对象和DOMText对象,所有这

个email地址在$nodes[0]->nodeVlue

When you know that you’re only interested in the text portion of a node, use the functionString( ) function.

This function converts nodes to PHP strings, which allows you to omit the array access and nodeValue

dereference:

当你知道唯一的在正文部分的一个网点。使用这个functionString(()函数,这个函数转换nodes到PHP字符串。那个允许你忽

略数组的访问和nodeValue参照


function mangle_email($email) {
    return preg_replace('/([^@\s]+)@([-a-z0-9]+\.)+[a-z]{2,}/is',
                        ‘$1@…’,
                        $email);
}
// all other code is the same as before

The new stylesheet template for /address-book/person/email is:
这个新的stylesheet模板对于/address-book/person/email是

<xsl:template match="/address-book/person/email">
  <xsl:copy>
    <xsl:value-of
       select="php:functionString('mangle_email', node())" />
  </xsl:copy>
</xsl:template>

The mangle_email( ) function now processes $email instead of $nodes[0]->nodeValue because the template now

calls the functionString( ) function.

这个mangle_email()函数处理$email代替$nodes[0]->nodeValue因为这个模板调用functionString()函数
 

12.8设置XSLT参数从PHP中

12.8.1问题

You want to set parameters in your XSLT stylesheet from PHP.

你想要设置你的XSLT参数从PHP中

12.8.2解答
Use the XSLTProcessor::setParameter( ) method:

使用这个XSLTProcessor::setParameter()方法

// This could also come from $_GET['city'];
$city = 'San Francisco';
$dom  = new DOMDocument
$dom->load('address-book.xml');
$xsl  = new DOMDocument
$xsl->load('stylesheet.xsl');
$xslt = new XSLTProcessor();
$xslt->importStylesheet($xsl);
$xslt->setParameter(NULL, 'city', $city);
print $xslt->transformToXML($dom);

This code sets the XSLT city parameter to the value stored in the PHP variable $city.

这个代码设置XSLT参数到这个存储数值在PHP的变量$city

12.8.3讨论
You can pass data from PHP into your XSLT stylesheet with the setParameter( ) method. This allows you to do

things such as filter data in your stylesheet based on user input.

你可以通过PHP到你的XSLT类型和这个setParameter()方法、它允许你例如过滤数据到你的stylesheet早使用者的输出

For example, the program in Example 12-16 allows you to find people based on their city.
例如。这个程序在例子12-16允许你去寻找people在他们的city


// This could also come from $_GET['city'];
$city = 'San Francisco';
$dom  = new DOMDocument
$dom->load('address-book.xml');
$xsl  = new DOMDocument
$xsl->load('stylesheet.xsl');
$xslt = new XSLTProcessor();
$xslt->importStylesheet($xsl);
$xslt->setParameter(NULL, 'city', $city);
print $xslt->transformToXML($dom);

The program uses the following stylesheet:

这个程序使用下列stylesheet

<?xml version="1.0" ?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform“>
<xsl:template match=”@*|node()”>
  <xsl:copy>
    <xsl:apply-templates select=”@*|node()”/>
  </xsl:copy>
</xsl:template>
<xsl:template match=”/address-book/person”>
  <xsl:if test=”city=$city”>
    <xsl:copy>
      <xsl:apply-templates select=”@*|node()”/>
    </xsl:copy>
  </xsl:if>
</xsl:template>
</xsl:stylesheet>

The program and stylesheet combine to produce the following results:

这个程序和stylesheet联合录制下列结果
<code>
<?xml version=”1.0″?>
<address-book>
    <person id=”2″>
        <!–Adam Trachtenberg–>
        <firstname>Adam</firstname>
        <lastname>Trachtenberg</lastname>
        <city>San Francisco</city>
        <state>CA</state>
        <email>amt@php.net</email>
    </person>
</address-book>

The PHP script does a standard XSLT transformation, except that it calls $xslt->setParameter(NULL, ‘city’,

$city). The first argument is the parameter’s namespace, the second is the parameter’s name, and the third is

the parameter’s value.

这个PHP原本是一个标准XSLT转换。除了它调用$xslt->setParameter(NULL.’city’.$city)这第一个论点是这个参数。这第二

个论点是名字。第三个是参数的值

Here, the value stored in the PHP variable $city’in this case, San Francisco’is assigned to the XSLT

parameter city, which does not live under a namespace. This is equal to placing the following in an XSLT

file:

这里。这个数值存储在PHP变量$city。San Francisco的分配到这个XSLT参数city。哪个不能在一个名字下面。他们
相等于下列一个XSLT文件

<xsl:param name="city">San Francisco</xsl:param>

You usually access a parameter inside a stylesheet like you do a PHP variable, by placing a dollar sign ($)

in front of its name. The stylesheet example creates a template that matches /address-book/person nodes.
你经常访问一个参数在一个内部。像你的一个PHP变量在变量前面加一个$.这个stylesheet例子创造一个模块匹配网点

Inside the template, you test whether city=$city; in other words, is the city child of the current node equal

to the value of the city parameter? If there’s a match, the children are copied along; otherwise, the records

are eliminated.
在这个模板内部。你测试city=$city。换句话说。在这个city类相等的数值city 惨呼。如果匹配。这个子类将复制。另外。

记录将消除

In this case, city is set to San Francisco, so David’s record is removed and Adam’s remains.

既然这样。city到San Francisco、所以David的记录远离remains

12.7转换XML为XSLT

12.7.1问题

You have an XML document and an XSL stylesheet. You want to transform the document using XSLT and capture the

results. This lets you apply stylesheets to your data and create different versions of your content for

different media.

你有一个XML文件和一个XSL stylesheet, 你想要转换文件使用XSLT和capure这个结果。它将你应用你的数据和创造不同的

版本在不同的媒体

12.7.2解答
Use PHP’s XSLT extension
使用PHP的XSLT延展名


// Load XSL template
$xsl = newDOMDocument;
$xsl->load('stylesheet.xsl');
// Create new XSLTProcessor
$xslt = new XSLTProcessor();
// Load stylesheet
$xslt->importStylesheet($xsl);
// Load XML input file
$xml = new DOMDocument;
$xml->load('data.xml');
// Transform to string
$results = $xslt->transformToXML($xml);
// Transform to a file
$results = $xslt->transformToURI($xml, 'results.txt');
// Transform to DOM object
$results = $xslt->transformToDoc($xml);

The transformed text is stored in $results
这个转换正文存储在$results

12.7.3讨论

XML documents describe the content of data, but they don’t contain any information about how that data should

be displayed. However, when XML content is coupled with a stylesheet described using XSL (eXtensible

Stylesheet Language), the content is displayed according to specific visual rules.

XML文件描述这个数据的内容。但是它不能包含一些必须显示的数据。当XML内容联合一个描述使用XSL、这个内容显示依照特

殊的规则

The glue between XML and XSL is XSLT (eXtensible Stylesheet Language Transformations). These transformations

apply the series of rules enumerated in the stylesheet to your XML data. So just as PHP parses your code and

combines it with user input to create a dynamic page, an XSLT program uses XSL and XML to output a new page

that contains more XML, HTML, or any other format you can describe
结合XML和XSL是XSLT这些转换应用列举规则在这你的XML数据风格,所以如果你的PHP分列你的代码和结合到使用者输出创造

一个动态页面。一个XSLT程序使用XSL和XML去输出一个新的页面包含更多的XML.HTML或者一些其他的格式

There are a few XSLT programs available, each with different features and limitations. PHP 5 supports only

the libxslt processor. This is a different processor than PHP 4 used
这是一个少量的XSLT程序变量。每个不同的的特质和限制,PHP5支持唯一的libxslt处理它是一个不同的处理跟PHP4相比
Using XSLT in PHP 5 involves two main steps: preparing the XSLT object and then triggering the actual

transformation for each XML file.

使用XSLT在PHP5包括两个主要的:准备XSLT对象和控制真正的变化到每个XML文件


// Load XSL template
$xsl = newDOMDocument;
$xsl->load('stylesheet.xsl');
// Create new XSLTProcessor
$xslt = new XSLTProcessor();
// Load stylesheet
$xslt->importStylesheet($xsl);

Now the transformer is up and running. You can transform any DOM object in one of three ways: into a string,

into a file, or back into another DOM object, as shown in Example 12-15.

现在这个变化的运动、你可以转换DOM对象在第三个路线、在一个字符串内的一个文件或者其他DOM对象。例如在例子12-15

// Load XML input file
$xml = new DOMDocument;
$xml->load('data.xml');
// Transform to string
$results = $xslt->transformToXML($xml);
// Transform to a file
$results = $xslt->transformToURI($xml, 'results.txt');
// Transform to DOM object
$results = $xslt->transformToDoc($xml);

When you call transformToXML( ) or transformToDoc( ), the extension returns the result string or object. In

contrast, transformToURI( ) returns the number of bytes written to the file, not the actual document.

当你调用transformToXML()或者transformToDoc()。这个延展名返回字符串结果或者对象对比transformtourl()返回这个
字节数字、不是真是的文件
 

12.6提取信息使用XPath

12.6.1问题
You want to make sophisticated queries of your XML data without parsing the document node by node.

你想要制造一个查询在你的XML数据和分解这个文件网点

12.6.2解答

Use XPath.
使用XPath
XPath is available in SimpleXML:
XPath是简单的可利用的

?php
$s = simplexml_load_file('address-book.xml');
$emails = $s->xpath('/address-book/person/email');
foreach ($emails as $email) {
    // do something with $email
}

And in DOM:

然后在DOM

?php
$dom = new DOMDocument;
$dom->load('address-book.xml');
$xpath = new DOMXPath($dom);
$email = $xpath->query('/address-book/person/email');
foreach ($emails as $email) {
    // do something with $email
}

12.6.3讨论
Except for the simplest documents, it’s rarely easy to access the data you want one element at a time. As your XML files become increasingly complex and your parsing desires grow, using XPath is easier than filtering the data inside a foreach.

除了简单的文件。它很容易去访问这个数据在你想要的一个元素。当作你的XML文件变成复杂的和你的分解要求生成。使用XPath是更加简单的过滤数据在一个foreach

PHP has an XPath class that takes a DOM object as its constructor. You can then search the object and receive DOM nodes in reply. SimpleXML also supports XPath, and it’s easier to use because it’s integrated into the SimpleXML object.

PHP有一个XPath类有一个DOM对象当作构造器。你可以搜索这个对象和接受DOM网点在这个回复。SimpleXML同样支持Xpath.然后容易使用因为它统一到一个SimpleXML对象
DOM supports XPath queries, but you do not perform the query directly on the DOM object itself. Instead, you create a DOMXPath object, as shown in Example 12-9.

DOM支持XPath查询。但是它不直接履行查询,例如在例子12-9

$dom = new DOMDocument;
$dom->load('address-book.xml');
$xpath = new DOMXPath($dom);
$email = $xpath->query('/address-book/person/email');

Instantiate DOMXPath by passing in a DOMDocument to the constructor. To execute the XPath query, call query( ) with the query text as your argument. This returns an iterable DOM node list of matching nodes (see Example 12-10).
例示DOMPath通过在一个DOMDocument 到这个构造器,去执行这个XPath查询。调用query()和query正文当作你的论点。它返回一个iterable DOM网点,看例子12-10

Using XPath with DOM in a basic example

$dom = new DOMDocument;
$dom->load('address-book.xml');
$xpath = new DOMXPath($dom);
$emails = $xpath->query('/address-book/person/email');
foreach ($emails as $e) {
    $email = $e->firstChild->nodeValue;
    // do something with $email
}

After creating a new DOMXPath object, query this object using DOMXPath::query( ), passing the XPath query as the first parameter (in this example, it’s /people/person/email). This function returns a node list of matching DOM nodes.
经过创造一个新的DOMXPath对象。查询这个对象使用DOMPath::query()。通过这个XPath query当作第一个参数
By default, DOMXPath::query( ) operates on the entire XML document. Search a subsection of the tree by passing in the subtree as a final parameter to query( ). For instance, to gather all the first and last names of people in the address book, retrieve all the people nodes and query each node individually, as shown in Example 12-11.

定义DOMXPath::query()操作在全部的XML文件。搜索一个分段的tree通过子树当作一个最后的参数到query(),例如集合所有的第一个和最后一个名字在这个住址名册。找回所有的people网点和查询每个个别的node,例如在例子12-11

$dom = new DOMDocument;
$dom->load('address-book.xml');
$xpath = new DOMXPath($dom);
$person = $xpath->query('/address-book/person');
foreach ($person as $p) {
    $fn = $xpath->query('firstname', $p);
    $firstname = $fn->item(0)->firstChild->nodeValue;
    $ln = $xpath->query('lastname', $p);
    $lastname = $ln->item(0)->firstChild->nodeValue;
    print "$firstname $lastname\n";
}
David Sklar
Adam Trachtenberg

Inside the foreach, call DOMXPath::query( ) to retrieve the firstname and lastname nodes. Now, in addition to the XPath query, also pass $p to the method. This makes the search local to the node.

在foreach内部,调用DOMXPath::query()重新找回第一个名和最后一个名nodes,现在在除了XPath查询。同样通过$p到这个方法。它确定搜索本地node

In contrast to DOM, all SimpleXML objects have an integrated xpath( ) method. Calling this method queries the current object using XPath and returns a SimpleXML object containing the matching nodes, so you don’t need to instantiate another object to use XPath. The method’s one argument is your XPath query.
和DOM对比。所有的SimpleXML对象有一个综合的xpath()方法。调用这个方法查询这个正确的对象使用XPath和返回一个SimoleXML对象包含匹配的nodes。所以你不需要例示其他对象使用XPath。这个方法的一个论点是你的XPath查询
Use Example 12-12 to find all the matching email addresses in the sample address book.

使用例子12-12去寻找所有的匹配email地址。在这个住址名册

$s = simplexml_load_file('address-book.xml');
$emails = $s->xpath('/address-book/person/email');
foreach ($emails as $email) {
    // do something with $email
}

This is shorter because there’s no need to dereference the firstNode or to take the nodeValue.

这个是简短的。因为它不需要废弃第一个站点或者获得价值

SimpleXML handles the more complicated example, too. Since xpath( ) returns SimpleXML objects, you can query them directly, as in Example 12-13.

SimpleXML也有很多复杂的例子。从xpath()返回Simple对象。你可以直接查询,例如在例子12-13


$s = simplexml_load_file('address-book.xml');
$people = $s->xpath('/address-book/person');
foreach($people as $p) {
    list($firstname) = $p->xpath('firstname');
    list($lastname) = $p->xpath('lastname');
    print "$firstname $lastname\n";
}
David Sklar
Adam Trachtenberg

Since the inner XPath queries return only one element, use list to grab it from the array.

从这个内部的XPath查询返回唯一的元素。使用目录夺取它的数组

12.5分解巨大的XML文件

12.5.1问题
You want to parse a large XML document. This document is so large that it’s impractical to use SimpleXML or DOM because you cannot hold the entire document in memory. Instead, you must load the document in one section at a time.

你想要分解一个巨大的XML文件。这个文件是非常大、不切实际的使用SimpleXML或者DOM.因为你不希望全部的文件在memory。代替。你必须装在文件在一个部分

12.5.2解答
Use the XMLReader extension:

使用这个XMLReader延长名


?php
$reader = new XMLReader();
$reader->open('card-catalog.xml');
/* Loop through document */
while ($reader->read()) {
    /* If you're at an element named 'author' */
    if ($reader->nodeType == XMLREADER::ELEMENT && $reader->localName == 'author') {
        /* Move to the text node and print it out */
        $reader->read();
        print $reader->value . "\n";
    }
}

There are two major types of XML parsers: ones that hold the entire document in memory at once, and ones that hold only a small portion of the document in memory at any given time.

这是两个主要的XML剖析器类型、一个把握全部的文件在merory,然后一个希望唯一的小的一部分文件在memory在一些时间

The first kind are called tree-based parsers, since they store the document into a data structure known as a tree. The SimpleXML and DOM extensions, from Recipes 12.3 and 12.4, are tree-based parsers. Using a tree-based parser is easier for you, but requires PHP to use more RAM. With most XML documents, this isn’t a problem. However, when your XML document is quite large, then this can cause major performance issues.

这第一个调用tree-based的剖析器、从它们存储文件到一个数据结构是一个tree。这个SimpleXML和DOM扩展名从第12.3和12.4和tree-based剖析器对于你来说容易的。但是命令PHP去使用更多的RAM。和更多的XML文件。他不是一个问题。经当你的XML文件非常大。然后它导致主要的问题
The other kind of XML parser is a stream-based parser. Stream-based parsers don’t store the entire document in memory; instead, they read in one node at a time and allow you to interact with it in real time. Once you move onto the next node, the old one is thrown away’unless you explicitly store it yourself for later use. This makes stream-based parsers faster and less memory consuming, but you may have to write more code to process the document.
这个其他类型的XML剖析器是一个stream-based 

12.4分析复杂的XML文件

12.4.1问题
You have a complex XML document, such as one where you need to introspect the document to determine its

schema, or you need to use more esoteric XML features, such as processing instructions or comments.

你有一个复杂的XML文件。例如在你需要的内部文件去测定它的计划。或者你需要使用很多深奥的XML性质。例如处理指示或者

注释

12.4.2解答

Use the DOM extension. It provides a complete interface to all aspects of the XML specification
使用这个DOM延展名。它规定一个完整的界面到所有XML规范


?php
$dom = new DOMDocument;
$dom->load('address-book.xml');
foreach ($dom->getElementsByTagname('person') as $person) {
    $firstname = $person->getElementsByTagname('firstname');
    $firstname_text_value = $firstname->item(0)->firstChild->nodeValue;
    $lastname = $person->getElementsByTagname('lastname');
    $lastname_text_value = $lastname->item(0)->firstChild->nodeValue;
    print "$firstname_text_value $lastname_text_value\n";
}
David Sklar
Adam Trachtenberg

12.4.3讨论
The W3C’s DOM provides a platform- and language-neutral method that specifies the structure and content of a

document. Using the DOM, you can read an XML document into a tree of nodes and then maneuver through the tree

to locate information about a particular element or elements that match your criteria. This is called tree-

based parsing.
这个W3C’s DOM规定一个platform-和language-neutral 方法指定结构和内容的文件,使用这个DOM.你可以阅读一个XML文件到

一个tree站点然后机动穿过tree的站点信息的一个特殊元素或者元素匹配你的标准。它调用tree-based分解
 
Additionally, you can modify the structure by creating, editing, and deleting nodes. In fact, you can use the

DOM functions to author a new XML document from scratch; see Recipe 12.2.
另外、你可以修改结构创造。编辑和删除网点、事实上,你可以使用DOM函数去创造一个新的XML文件从新开始,看12.2 
One of the major advantages of the DOM is that by following the W3C’s specification, many languages implement

DOM functions in a similar manner. Therefore, the work of translating logic and instructions from one

application to another is considerably simplified. PHP 5 comes with a new series of DOM methods that are in

stricter compliance with the DOM standard than previous versions of PHP.
一个有主要优势的DOM文件跟随这个W3C’s详述。很多语言执行DOM函数在某种意义上相似因此、这个工作翻译逻辑和指示从一

个应用到另一个相当的PHP5伴随一个新增序列的DOM方法是一个严格的DOM标准 
The DOM is large and complex. For more information, read the specification at http://www.w3.org/DOM/ or pick

up a copy of XML in a Nutshell.
这个DOM是巨大的复杂。例如信息。阅读详细的在http://www.w3.org/DOM或者精选一份XML

DOM functions in PHP are object oriented. To move from one node to another, access properties such as $node-

>childNodes, which contains an array of node objects, and $node->parentNode, which contains the parent node

object. Therefore, to process a node, check its type and call a corresponding method, as shown in Example 12-

5.
DOM函数在PHP的对象倒像、去移动一个网点到其他访问道具例如$node->childNodes。哪个包含一个数组站点对象。和$node-

>parentNOde。哪个包含亲代交点。因此。处理一个node。组织它的类型和调用一个相应的方法,例如在例子12–5

Parsing a DOM object

?php
// $node is the DOM parsed node <book cover="soft">PHP Cookbook</book>
$type = $node->nodeType; 
switch($type) {
case XML_ELEMENT_NODE:
    // I'm a tag. I have a tagname property.
    print $node->tagName;  // prints the tagname property: "book"
    break;
case XML_ATTRIBUTE_NODE:
    // I'm an attribute. I have a name and a value property.
    print $node->name;  // prints the name property: "cover"
    print $node->value; // prints the value property: "soft"
    break;
case XML_TEXT_NODE:
    // I'm a piece of text inside an element.
    // I have a name and a content property.
    print $node->nodeName;  // prints the name property: "#text"
    print $node->nodeValue; // prints the text content: "PHP Cookbook"
    break;
default:
    // another type
    break;
}

To automatically search through a DOM tree for specific elements, use getElementsByTagname( ). Example 12-6

shows how to do so with multiple book records.
自动的搜索一个DOM tree对于特殊的元素、使用getElementByTagname()。例如12-6显示怎么去多多样的账面记录

Card catalog in XML
<books>
    <book>
        <title>PHP Cookbook</title>
        <author>Sklar</author>
        <author>Trachtenberg</author>
        <subject>PHP</subject>
    </book>
    <book>
        <title>Perl Cookbook</title>
        <author>Christiansen</author>
        <author>Torkington</author>
        <subject>Perl</subject>
    </book>
</books>

Example 12-7 shows how to find all authors.
例子12-7显示怎么去找到所有的作者

Printing all authors using DOM
// find and print all authors
$authors = $dom->getElementsByTagname('author');
// loop through author elements
foreach ($authors as $author) {
    // childNodes holds the author values
    $text_nodes = $author->childNodes;
    foreach ($text_nodes as $text) {
         print $text->nodeValue . "\n";
    }
}
Sklar
Trachte nberg
Christiansen
Torkington

12.2在DOM产生XML

12.2.1问题
You want to generate XML but want to do it in an organized way instead of using print and loops.

你想要产生XML。但是应该在一个organized路线代替使用print 和loops

12.2.2解答
Use the DOM extension to create a DOMDocument object. After building up the document, call DOMDocument::save(

) or DOMDocument::saveXML( ) to generate a well-formed XML document
使用这个DOM的延长区创造一个DOMDocument object、然后树立这个文件、调用DOMDocument::save()或者

DOMDocument::saveXML()去产生一个健康成型的文件

?php
// create a new document
$dom = new DOMDocument('1.0');
// create the root element, <book>, and append it to the document
$book = $dom->appendChild($dom->createElement('book'));
// create the title element and append it to $book
$title = $book->appendChild($dom->createElement('title'));
// set the text and the cover attribute for $title
$title->appendChild($dom->createTextNode('PHP Cookbook'));
$title->setAttribute('cover', 'soft');
// create and append author elements to $book
$sklar = $book->appendChild($dom->createElement('author'));
// create and append the text for each element
$sklar->appendChild($dom->createTextNode('Sklar'));
$trachtenberg = $book->appendChild($dom->createElement('author'));
$trachtenberg->appendChild($dom->createTextNode('Trachtenberg'));
// print a nicely formatted version of the DOM document as XML
$dom->formatOutput = true;
echo $dom->saveXML();
?>
<?xml version="1.0"?>
<book>
  <title cover="soft">PHP Cookbook</title>
  <author>Sklar</author>
  <author>Trachtenberg</author>
</book>

12.3.3讨论
The DOM methods follow a pattern. You create an object as either an element or a text node, add and set any

attributes you want, and then append it to the tree in the spot it belongs.
这个DOM方法允许仿制。你创造一个对象当作任意一个元素或者一个文件网点。增加移动一些你想要的属性。然后附加它到心

事驱动器的子目录结果
Before creating elements, create a new document, passing the XML version as the sole argument:
在创造元素之前。创造一个新建文档通过这个XML版本当作单一的论点

$dom = new DOMDocument('1.0');

Now create new elements belonging to the document. Despite being associated with a specific document, nodes

don’t join the document tree until appended:

现在创造一个新的元素属于文件。不管联合一个特殊文件网点不能链接文件直到设置数据文件的搜索路径


$book_element = $dom->createElement('book');
$book = $dom->appendChild($book_element);

Here a new book element is created and assigned to the object $book_element. To create the document root,

append $book_element as a child of the $dom document. The result, $book, refers to the specific element and

its location within the DOM object
这是一个新的文件元素创造分配到$book_element去保存这个文件证明,附加$book_element当作一个子类$dom文件。这个结果

$book,引用特殊的元素和位置内部DOM对象

All nodes are created by calling a method on $dom. Once a node is created, it can be appended to any element

in the tree. The element from which we call the appendChild( ) method determines the location in the tree 
所有的网点创造调用一个方法在$dom.从一个node创造,它可以附加一些元素在这个tree.这个元素从我们调用这个

appendChid()方法确定位置在这个tree,
You can also append a new child element to $book. Since $book is a child of $dom, the new element is, by

extension, a grandchild of $dom:

你同样可以附加一个新的子元素到$book.从$book是一个子类$dom。这个新的元素是延长一个孙类$dom


$title_element = $dom->createElement('title');
$title = $book->appendChild($title_element);

By calling $book->appendChild( ), this code places the $title_element element under the $book element.

调用$book->appendChild()。这个代码放置这个$titie_element .在这个$book元素

To add the text inside the <title></title> tags, create a text node using createTextNode( ) and append it to

$title:

去增加正文代替<title></title>标签,创造一个正文网点使用createTextNode()和append()它到$title


$text_node = $dom->createTextNode('PHP Cookbook');
$title->appendChild($text_node);

Since $title is already added to the document, there’s no need to re-append it to $book.

从$title是已经增加到这个文件。就不需要去附加到$book

$title_element = $dom->createElement('title');
$text_node = $dom->createTextNode('PHP Cookbook');
$title_element->appendChild($text_node);
$book->appendChild($title_element);

To add an attribute, call setAttribute( ) upon a node, passing the attribute name and value as arguments:

去增加一个属性。调用setAttribute()upon一个网点。通过这个attribute名字和数值当作论点

$title->setAttribute('cover', 'soft');

If you print the title element now, it looks like this:

如果你打印这个title元素。它会是这样

<title cover="soft">PHP Cookbook</title>

Once you’re finished, you can output the document as a string or to a file:

从前你完成。你可以输出文件就像一个字符串或者一个文件


// put the string representation of the XML document in $books
$books = $dom->saveXML();
// write the XML document to books.xml
$dom->save('books.xml');