12.1产生XML当作一个字符串

12.1.1问题
You want to generate XML. For instance, you want to provide an XML version of your data for another program to

parse.

你想要产生XML。例如。你想要规定一个XML版本的数据解析其他程序

12.1.2解答
Loop through your data and print it out surrounded by the correct XML tags:
通过你的数据打印出正确的XML标签

?php
header(’Content-Type: text/xml’);
print ‘<?xml version=”1.0″?>’ . “\n”;
print “<shows>\n”;
$shows = array(array(’name’     => ‘Simpsons’,
                     ‘channel’  => ‘FOX’,
                     ’start’    => ‘8:00 PM’,
                     ‘duration’ => ‘30′),

               array(’name’     => ‘Law & Order’,
                     ‘channel’  => ‘NBC’,
                     ’start’    => ‘8:00 PM’,
                     ‘duration’ => ‘60′));
foreach ($shows as $show) {
    print “    <show>\n”;
    foreach($show as $tag => $data) {
        print “        <$tag>” . htmlspecialchars($data) . “</$tag>\n”;
    }
    print “    </show>\n”;
}
print “</shows>\n”;;

12.1.3讨论
Printing out XML manually mostly involves lots of foreach loops as you iterate through arrays. However, there

are a few tricky details. First, you need to call header( ) to set the correct Content-Type header for the

document. Since you’re sending XML instead of HTML, it should be text/xml.

手动打印出XML主要的foreach当作你重复的数组。尽管这是一个详细资料。首先你需要钓鱼hearder()去获得正确的Content-

Type.对于这个文件。从你过的XML代替HTML.它的text/xml
Next, depending on your settings for the short_open_tag configuration directive, trying to print the XML

declaration may accidentally turn on PHP processing. Since the <? of <?xml version=”1.0″?> is the short PHP

open tag, to print the declaration to the browser you need to either disable the directive or print the line

from within PHP. We do the latter in the Solution.

下面。依靠你的设置去short_open_tag配置指示。试着打印出XML声明可以转换PHP处理。从这个<?到<?xml version=”1.0″?>

是这个短的PHP tag去打印出这个声明到浏览器 你需要的任意显示这个指示或者打印出PHP。我们有解答在后面
Last, entities must be escaped. For example, the & in the show Law & Order needs to be &amp;. Call

htmlspecialchars( ) to escape your data.

最后实体必须逃脱。例如这个&在这个表面&需要到&amo、调用htmlspecialchars()去逃开你的数据
The output from the example in the Solution is shown in Example 12-1.

这个输出这个例子在这个解答在例子12-1

<?xml version="1.0"?>
<shows>
    <show>
        <name>Simpsons</name>
        <channel>FOX</channel>
        <start>8:00 PM</start>
        <duration>30</duration>
    </show>
    <show>
        <name>Law &amp; Order</name>
        <channel>NBC</channel>
        <start>8:00 PM</start>
        <duration>60</duration>
    </show>
</shows>

  

Comments are closed.