解決 PHP XML 已經啟用 formatOutput = true 選項,輸出的 XML 還是擠成一團

參考 w3schools 的 XML 教學在 PHP addChild() Function 後,雖然已經啟用 formatOutput = true 選項,輸出的 XML 還是擠成一團。解決方式是去除換行符號後,再輸出。

PHP icon by Icons8


輸出 XML 擠成一圖可能還包含空白行:
<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from> 
<heading>Reminder</heading>
<body>Don't forget me this weekend!<date>2018-01-01</date></body>
<footer>Some footer text</footer></note>

修改後符合預期輸出的 XML:
<?xml version="1.0"?>
<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!<date>2018-01-01</date></body>
  <footer>Some footer text</footer>
</note>
PHP 檔案關鍵在於去除換行符號後,再輸出
<?php
$note = <<<XML
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
XML;
$xml = new SimpleXMLElement($note);
$xml->body->addChild("date","2018-01-01");

$footer = $xml->addChild("footer","Some footer text");

$xml_string = $xml->asXML();
echo '===='. PHP_EOL;
echo $xml_string . PHP_EOL;

    $dom = new DOMDocument;
    $dom->loadXML($xml_string);
    if (!$dom) {
        echo 'Error while parsing the document';
        exit;
    }
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput = true;
    $xml_file_content = $dom->saveXML();
echo '===='. PHP_EOL;
echo $xml_file_content;

$xml_string = str_replace(array("\r\n", "\n", "\r"), "", $xml_string);
echo '===='. PHP_EOL;
echo $xml_string . PHP_EOL;

    $dom = new DOMDocument;
    $dom->loadXML($xml_string);
    if (!$dom) {
        echo 'Error while parsing the document';
        exit;
    }
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput = true;
    $xml_file_content = $dom->saveXML();
echo '===='. PHP_EOL;
echo $xml_file_content;
?>
相關資料


留言