Reputation: 33048
I'm attempting to modify an xml file with DOMDocument. What I have is working, but it's adding more modifications to the xml file than I asked for.
Code:
$sDB = $this->oDB->getDBName();
$file = 'test.xml';
// Load XML
$dom = new DOMDocument;
$dom->preserveWhiteSpace = true;
$dom->formatOutput = false;
$dom->validateOnParse = false;
$dom->load($file);
// Find TEST Node
$nodes = $dom->getElementsByTagName('parameter');
foreach($nodes as $node)
{
if($node->getAttribute('name') == 'TEST')
{
$sBDC = $node->nodeValue;
$aBDC = explode(',',$sBDC);
if(!in_array($sDB,$aBDC))
array_push($aBDC,$sDB);
$sBDC = implode(',',$aBDC);
$node->nodeValue = $sBDC;
$dom->save($file);
break;
}
}
Some of the XML:
<parameter name="Integration" username="testuser" password="testpassword">/parameter>
<parameter name="API">accept.php</parameter>
<parameter name="TRANSFER" username="admin" password="letmein" />
<parameter name="TEST">dbname</parameter>
The problem:
It's adding <?xml version="1.0"?>
to the beginning of the XML file and it's modifying some of the <parameter>
elements by making any unnecessary ending tags inline if there is no value. For example <parameter name="email"></parameter>
would become <parameter name="email" />
. It's also removing some other unnecessary white space within the elements.
While my gut instinct is telling me these changes won't hurt anything, I'd feel much more comfortable with this if the only changes taking place were the intended ones. Unfortunately, it wouldn't surprise me if there was some code buried somewhere that's actually looking for these unnecessary white-spaces.
Upvotes: 1
Views: 73
Reputation: 78974
Well, a valid XML file will have the XML definition. Also, you can keep it from using the self closing tags by using LIBXML_NOEMPTYTAG
flag in the save()
.
Upvotes: 1