使用PHP从xml中删除空节点

问题描述 投票:1回答:1

下面是我的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>
php xml
1个回答
0
投票

假设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();
?>

live code

在此示例中,$data["height"]设置为空字符串。它也可以设置为NULL。如果它根本没有设置,则empty()仍然有效,但会出现一个通知,抱怨未定义的索引“height”;见here

如果问题与已经存在的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

live code

此示例还使用了PHP 7功能,即immediately invoked function expression(iffe)。

警告:如果你使用带有heredoc的关联数组,请避免在元素名称周围使用任何类型的引号,否则你的代码会产生错误;好读here

© www.soinside.com 2019 - 2024. All rights reserved.