You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP创建嵌套XML时格式异常,如何实现正确缩进结构?

问题描述

使用以下PHP代码生成XML时:

<?php 
    $dom = new DOMDocument();
    $document = $dom->appendChild(
      $dom->createElement('xtranslation') 
    );
    $document->textContent = '21st Century King James Version';
    
    $document->appendChild($dom->createElement('xabbreviation'))->textContent = 'KJ21';

    $dom->formatOutput = true;
    echo $dom->saveXml();
?>

生成的XML是内联结构:

<?xml version="1.0"?>
<xtranslation>21st Century King James Version<xabbreviation>KJ21</xabbreviation></xtranslation>

期望得到带正确缩进的嵌套结构:

<?xml version="1.0"?>
<xtranslation>21st Century King James Version
  <xabbreviation>KJ21</xabbreviation>
</xtranslation>

移除$document->textContent = '21st Century King James Version';后格式正常,需在保留文本内容的前提下实现正确格式。

解决方案

DOMDocument的formatOutput对**混合内容(文本节点+元素节点)**不会自动添加换行和缩进,因为它默认会保留文本的空白语义。要实现预期格式,需手动添加包含换行和缩进的空白文本节点,具体代码如下:

<?php 
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true;

// 创建父元素
$xtranslation = $dom->appendChild($dom->createElement('xtranslation'));

// 添加主文本节点
$xtranslation->appendChild($dom->createTextNode('21st Century King James Version'));

// 添加换行+缩进的空白节点
$xtranslation->appendChild($dom->createTextNode("\n  "));

// 创建并添加子元素
$xabbreviation = $xtranslation->appendChild($dom->createElement('xabbreviation'));
$xabbreviation->textContent = 'KJ21';

// 添加换行节点,让闭合标签单独一行
$xtranslation->appendChild($dom->createTextNode("\n"));

echo $dom->saveXml();
?>

运行后生成的XML:

<?xml version="1.0" encoding="UTF-8"?>
<xtranslation>21st Century King James Version
  <xabbreviation>KJ21</xabbreviation>
</xtranslation>
原理说明
  • 直接设置textContent会覆盖父元素内所有现有节点,后续添加子元素时,DOM不会自动在文本和元素之间插入空白(混合内容的空白可能存在语义意义)
  • 手动添加空白文本节点,明确指定换行和缩进格式,既能保留原文本内容,又能实现预期的排版结构

内容的提问来源于stack exchange,提问作者Äsiri Läkämäl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 05:20:30