php - 在 HTML 中显示 XML

标签 php html xml

我正在尝试在 HTML 中显示原始 XML。如果没有 HTML 元素,则 XML 可以正常显示 但是,一旦我添加内容,就会出现此错误

error on line 37 at column 6: XML declaration allowed only at the start of the document

在做了一些研究之后,这个问题很常见,有空格,但我没有注意到。这是我的源代码。

<?php require 'header.php'; ?>
<div class="sixteen columns">
<h3>XML</h3>
<?php 
header("Content-Type:text/xml");//Tell browser to expect xml
include("config/init.php");
$connection = mysqli_connect($hostname, $username, $password, $databaseName) or die("you did not connect");
$query = "SELECT * FROM art";
$result = mysqli_query($connection, $query) or die (mysqli_error($connection));
//Top of xml file
$_xml = '<?xml version="1.0" encoding="UTF-8"?>';
$_xml .="<art>"; 
while($row = mysqli_fetch_array($result)) { 
$_xml .="<art>"; 
$_xml .="<art_name>".$row['name']."</art_name>"; 
$_xml .="<art_category>".$row['category']."</art_category>"; 
$_xml .="<art_price>".$row['price']."</art_price>"; 
$_xml .="</art>"; 
} 
$_xml .="</art>"; 
//Parse and create an xml object using the string
$xmlobj=new SimpleXMLElement($_xml);
print $xmlobj->asXML();
$xmlobj->asXML('art.xml');
?>
</div>  
<?php require 'footer.php'; ?>

http://www.acalvert.x10host.com/xml.php如果你想查看页面源代码

最佳答案

如果您希望显示标记,则更改所有 <&lt;>&gt; .

在显示任何内容之前将您的 XML 加载到字符串变量并使用它:

$before = array('<','>');
$after = array('&lt;','&gt;');
$xml = str_replace($before,$after,$xml);
echo $xml;

其次 - 你不能调用 header()显示任何字符后的功能。根本不要使用它。你想要默认 text/html在您的文档中。

关于php - 在 HTML 中显示 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27305599/

相关文章:

python - 生成具有正确缩进的 XML 文件

php - 限制每个循环的查询结果

javascript - 提交按钮在 Chrome 中不起作用,但在 Firefox 中起作用

PHP try/catch 和 fatal error

android - 滚动文本滞后

JQuery mobile -> .append() 删除 CSS?

php - 使用 if 语句显示 JOIN 的多个结果

javascript - 一个 "unstyle"如何成为一个 div html 元素?

jQuery 在设置另一个 div 的高度时正在移动 div

javascript - 使用溢出滚动和中心在另一个 div 内缩放 div