<?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'] )
);
#$author->appendChild( $doc->createTextNode( 'pavunkumar'));
$new = $doc->createElement("Developer");
$a=$doc->createTextNode('I am developer ' );
$new->appendChild($a);
$b->appendChild( $author );
$b->appendChild($new);
$b->appendChild($new);
$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() ;
?>
当我在命令行中运行此代码时。我正在关注事情
<?xml version="1.0"?>
<books>
<book>
<author>Jack Herrington</author>
<Developer>I am developer </Developer>
<title>PHP Hacks</title>
<publisher>O'Reilly</publisher>
</book>
<book>
<author>Jack Herrington</author>
<Developer>I am developer </Developer>
<title>Podcasting Hacks</title>
<publisher>O'Reilly</publisher>
</book>
</books>
当我在网络浏览器中运行代码时,它为我提供了以下内容
Jack Herrington I am developer O'Reilly Jack Herrington I am developer O'Reilly
我希望上面的输出像命令行输出一样。还有一件事是,我不是要显示,而是如何使用$ doc Dom对象创建一个xml文件。
答案 0 :(得分:1)
我可能不正确,但尝试发送类似的标题:
Header("Content-Type: text/xml");
或
Header("Content-Type: text/plain");
取得适当的结果。 (当然在你运行$doc->saveXML();
之前。
答案 1 :(得分:1)
转换&lt;和&gt;使用htmlspecialchars(http://ua.php.net/manual/en/function.htmlspecialchars.php)的实体,浏览器不会将其解析为html:
echo htmlspecialchars($doc->SaveXml());
答案 2 :(得分:0)
这是因为您正在将XML代码输出到PHP文件中(翻译成HTML)。检查您的源代码,您将看到所需的输出。如果你想获得与命令行相同的东西,你必须将输出保存到新的XML文件。
使用fopen创建新的XML文件。