Php xml how to create/add attribute xsi:nil="true"

1.9k views Asked by At

Trying to get such output

<DeclarationFile>
<Declaration Id="DEC">
<DokPVNv4>
<ParskMen>5</ParskMen>
<ParskCeturksnis xsi:nil="true"/>

Can not create <ParskCeturksnis xsi:nil="true"/>

If use just

$ParskCeturksnis = new SimpleXMLElement("<ParskCeturksnis></ParskCeturksnis>");
$ParskCeturksnis->addAttribute("xsi:nil", "true", "http://www.w3.org/2001/XMLSchema-instance"); 
echo $ParskCeturksnis->asXml();

all works

But if whole code

$DOM = new DOMDocument('1.0','UTF-8');

$DeclarationFile = $DOM->createElement('DeclarationFile');
$DOM->appendChild($DeclarationFile);

$Declaration = $DOM->createElement('Declaration');
$DeclarationFile->appendChild($Declaration);
$Declaration_att = $DOM->createAttribute('Id');
$Declaration->appendChild($Declaration_att);
$att_Declaration_text = $DOM->createTextNode('DEC');
$Declaration_att->appendChild($att_Declaration_text);

$DokPVNv4 = $DOM->createElement('DokPVNv4');
$Declaration->appendChild($DokPVNv4);

$ParskMen = '5';
$ParskMen = $DOM->createElement('ParskMen',mb_convert_encoding($ParskMen, "UTF-8") );
$DokPVNv4->appendChild($ParskMen);

$ParskCeturksnis = new SimpleXMLElement("<ParskCeturksnis></ParskCeturksnis>");
$ParskCeturksnis->addAttribute("xsi:nil", "true", "http://www.w3.org/2001/XMLSchema-instance"); 
echo $ParskCeturksnis->asXml();

echo $DOM->saveXML(); 

get error XML Parsing Error: junk after document element

Searched google, but have not found solution....

Tried

 $ParskCeturksnis = $DOM->createElement('ParskCeturksnis');
 $DokPVNv4->appendChild($ParskCeturksnis)->addAttribute("xsi:nil", "true", "http://www.w3.org/2001/XMLSchema-instance");

get XML Parsing Error: no element found

1

There are 1 answers

1
IMSoP On BEST ANSWER

You seem to be confusing the SimpleXML and DOM extensions. While they are both implemented on top of the same parser, and can be switched between easily using dom_import_simplexml() and simplexml_import_dom(), that doesn't mean you can simply call methods which work on one on objects created by the other.

In your case, you are primarily using the DOM, so you need to add your attribute using the appropriate DOM functions, specifically ->createAttributeNS() and ->appendChild().

I think the code you need is this:

$ParskCeturksnis = $DOM->createElement('ParskCeturksnis');
$ParskCeturksnis->appendChild($DOM->createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi:nil"));
$DokPVNv4->appendChild($ParskCeturksnis);