使用PHP生成XML

时间:2012-12-27 09:16:51

标签: php xml

我想使用PHP从XML文件创建一些XML,但我无法使其工作

XML文件

<?xml version="1.0">
<streams>
  <stream>test</stream>
</streams>

PHP

<?php
  header("Content-type: text/xml");
  $xml = simplexml_load_file("t.xml");

  $html = "<?xml version='1.0'>";
  $html = $html . "<streams>";
  foreach($xml->stream as $stream) 
  {
    $html= $html . "<stream>";
    $html = $html . "<![CDATA[" . $stream->title . "]]>";
    $html= $html . "</stream>";
  }
  $html = $html . "</streams>";

  echo $html; 
?>

错误

Error: This page contains the following errors: error on line 2 at column 1: 
Extra content at the end of the document Below is a rendering of the page up
to the first error.

3 个答案:

答案 0 :(得分:2)

我会使用php simplexml来构建xml,而不是使用字符串

$xml = new SimpleXMLElement('<xml/>');
$streams = $xml->addChild('streams');
$steams->addChild('stream', 'data');
echo $xml->asXML();

就像提示一样,有一个连接字符串的简写:

$html = "<?xml version='1.0'?>";
$html .= "<streams>"; 
...

答案 1 :(得分:1)

首先:xml坏了,它必须是:

<?xml version="1.0"?>
-------------------^

(缺少问号,PHP脚本中也缺少问号)

然后:<stream/>

中没有title-element

它将按预期使用此xml:

<?xml version="1.0"?>
<streams>
  <stream><title>test</title></stream>
</streams>

答案 2 :(得分:-1)

我使用以下代码。我不知道它是否是最好的方式,但它确实有效。 我会把它作为评论键入,但我无法使“代码”格式起作用。

<?php
header("Content-type: text/xml");
echo "<?xml version='1.0' encoding='ISO-8859-1'?>";
  $source = "t.xml";
  $stream = new SimpleXMLElement($source,null,true);

  echo "<streams>";
  foreach($stream as $stream) {
    echo "<stream>";
    echo "<![CDATA[ . {$stream->title} . ]]>";

    echo "</stream>";
  }
  echo "</streams>";
?>