Assuming that the OP intends for the height and width to be the same, as the OP's code is written, and if the OP's question only pertains to generating XML, you may code the following:
<?php
// suppose some data is missing...
function generateXML(){
$data = [];
$data["height"]="";
$data["text"]="just a 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();
?>
See live code
In this example $data["height"]
is set to an empty string. It could also be set to NULL. If it is not set at all, empty() will still work but a notice will appear complaining about an undefined index "height"; see here.
If the question instead pertains to XML that already exists, then one may use a heredoc and PHP's support for the Document Object Model (DOM), as follows:
<?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
See live code
This example also makes use of a PHP 7 feature, an immediately invoked function expression (iffe).
Caveat: If you use an associative array with a heredoc, avoid using quotes of any kind around the element's name, otherwise your code will yield an error;
good read here