簡體   English   中英

PHP-格式化XML輸出

[英]PHP - Format XML Output

我正在生成一些XML數據以響應HTTP POST請求。 我正在設置MIME

header('Content-type: text/xml');

到目前為止一切正常。

我正在生成xml響應,如下所示:

 $response = '<?xml version="1.0" encoding="utf-8"?>';
 $response .= '<error>';
 $response .= '<description>'.$error.'</description>';
 $response .= '</error>';
 echo $response;

我現在想要格式化XML,以便不要看到此響應:

<?xml version="1.0" encoding="utf-8"?><error><description>Login Error: No Username Supplied</description></error>

他們看到以下響應:

<?xml version="1.0" encoding="utf-8"?>
 <error>
    <description>Login Error: No Username Supplied</description>
 </error>

在此之前,我還沒有使用PHP處理XML輸出,因此不確定是否有內置方法在輸出上執行“漂亮打印”類型的功能?

使用DOM庫並將formatOutput屬性設置為true

$doc = new DOMDocument('1.0', 'utf-8');
$doc->formatOutput = true;

$root = $doc->createElement('error');
$doc->appendChild($root);

$desc = $doc->createElement('description', $error);
$root->appendChild($desc);

echo $doc->saveXML();

演示〜https ://eval.in/461384

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM