簡體   English   中英

使用PHP從xml刪除空節點

[英]Remove empty nodes from xml using PHP

以下是我的xml內容,我只想返回非示例性標簽

$xml = '<template>' .
    '<height>' . $data['height'] . '</height>' .
    '<width>' . $data['height'] . '</width>' .
    '<text>' . $data['text'] . '</text>' .
    '</template>';

return $xml;

這里的輸出

<template><height></height><width>ddddd</width><text></text>/template>

假定OP希望高度和寬度保持不變,因為編寫了OP的代碼,並且如果OP的問題僅與生成XML有關,則可以編寫以下代碼:

<?php
// suppose some data is missing...
function generateXML(){
$data = [];
$data["height"]="";
$data["text"]="just&nbsp;a&nbsp;test";


$xml = "<template>";
$xml .= empty($data["height"])? "" : "<height>$data[height]</height><width>$data[height]</width>";

$xml .= empty($data["text"])? "" : "<text>$data[text]</text>";

$xml .= "</template>";
return $xml;
}
echo generateXML();
?>

查看實時代碼

在此示例中, $data["height"]設置為空字符串。 也可以將其設置為NULL。 如果根本沒有設置,empty()仍然可以工作,但會出現一條通知,提示未定義的索引“ height”; 這里

如果該問題與已經存在的XML有關,則可以使用heredoc和PHP對文檔對象模型( DOM )的支持,如下所示:

<?php

// suppose some data is missing...
$data = [];
$data["height"]="";
$data['text']="more testing";

// get XML into a variable ...
$xml = <<<XML
    <template>
        <height>$data[height]</height>
        <width>$data[height]</width>
        <text>$data[text]</text>
    </template>
XML;


    $dom = new DOMDocument;
    $dom->preserveWhiteSpace = false;
    $dom->loadXML( $xml );
    $template = $dom->getElementsByTagName('template')->item(0); 
    $nodeList = $template->childNodes;

    echo (function() use($dom,$template,$nodeList){
       // iterate backwards to remove node missing value 
       for( $max=$nodeList->length-1, $i=0; $max >= $i; $max-- ) {
          $currNode = $nodeList->item($max);
          $status = $currNode->hasChildNodes()? true:false;
          if ($status === false) {
             $currNode->parentNode->removeChild( $currNode );
          }// end if
       }// end for
       return $dom->saveXML( $template );
    })(); // immediate executable

查看實時代碼

此示例還利用了PHP 7功能,即立即調用的函數表達式 (iffe)。

注意:如果將帶關聯數組與Heredoc一起使用,請避免在元素名稱周圍使用任何類型的引號,否則代碼將產生錯誤; 好在這里

暫無
暫無

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

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