0

I'm trying to replicate this XML structure. The only thing I'm unable to handle is the initial declaration. Let me quote the most relevant part.

<p:FatturaElettronica versione="FPA12" xsi:schemaLocation="http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2 http://www.fatturapa.gov.it/export/fatturazione/sdi/fatturapa/v1.2/Schema_del_file_xml_FatturaPA_versione_1.2.xsd">

If I view the source code I see that in reality this statement is like follows.

<?xml version="1.0" encoding="UTF-8"?>
<p:FatturaElettronica versione="FPA12" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" 
xmlns:p="http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2 http://www.fatturapa.gov.it/export/fatturazione/sdi/fatturapa/v1.2/Schema_del_file_xml_FatturaPA_versione_1.2.xsd">

There's the p: namespace and the related xmlns:p attribute and I've no idea of how I should implement it in my PHP SimpleXMLElement script.

It's 2 days that I'm playing with namespaces in addChild and addAttribute and reading tutorials with no success. I give up. I reverted all changes to the following statemnt that is obviously wrong.

$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><FatturaElettronica versione="FPA12" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:p="http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2 http://www.fatturapa.gov.it/export/fatturazione/sdi/fatturapa/v1.2/Schema_del_file_xml_FatturaPA_versione_1.2.xsd"></FatturaElettronica>');

How the hell does it work? I've never been so stuck. Thank you for your time.

user1274113
  • 436
  • 8
  • 21

1 Answers1

1

SimpleXML has an unusual quirk where the namespace prefixes are filtered from the root element. I'm not sure why it does this.

However, a workaround I've used has been to basically prefix the prefix, so that the parser only removes the first ones, and leaves the second

$xmlTest = new SimpleXMLElement('<xmlns:ws:Test></xmlns:ws:Test>', LIBXML_NOERROR, false, 'ws', true);
$xmlTest->addAttribute('xmlns:xmlns:ws', 'http://url.to.namespace');
$xmlTest->addAttribute('xmlns:xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');

This seems to work for me, though I'm interested to understand why SimpleXML does this exactly.

Source

Ashly Taylor
  • 217
  • 1
  • 7
  • Thank you Ashly! Now I remember that I had the same issue months ago when dealing with XML Sitemaps. Frankly I don't get why I have to prefix the prefix :-| SimpleXML is so strange. Thank you again for your time! – user1274113 Oct 20 '18 at 12:11
  • thank you so much, was searching for hours.... – FalcoB Jun 30 '23 at 15:33