PHP浏览器格式化显示XML方法
本例详细讲解了如何使用PHP让浏览器以格式化方式呈现XML数据。该方案可供开发者参考与借鉴。
需要在脚本头部引入相关配置代码。
header("Content-type: application/xml");
初期尝试时并未成功,经过反复测试后找到关键步骤:在代码执行末端加入exit;即可生效。
$Dom = new \DOMDocument('1.0', 'utf-8');
$paper = $Dom->createElement('paper');
$Dom->appendChild($paper);
$exercises = $Dom->createElement('exercises');
$exercises->setAttribute('id','1');
$exercises->setAttribute('type','1');
$exercises->setAttribute('answer','1');
$paper->appendChild($exercises);
$title = $Dom->createElement('title');
$title->setAttribute('label','1');
$title->setAttribute('mapsrc','1');
$title->setAttribute('soundsrc','1');
$exercises->appendChild($title);
$option = $Dom->createElement('option');
$option->setAttribute('id','1');
$option->setAttribute('label','1');
$option->setAttribute('mapsrc','1');
$option->setAttribute('soundsrc','1');
$exercises->appendChild($option);
header("Content-type: application/xml");
echo $Dom->saveXml(); exit;

最终效果符合预期,显示效果良好。
此外,推荐以下XML操作在线工具供辅助使用:
提供XML与JSON相互转换的在线服务: 点击使用
支持XML在线格式化及压缩处理的服务: 点击使用
期望上述内容能对各位进行PHP开发提供有益帮助。