Search code examples
phpxmlsimplexml

XML Syntax attributes PHP - issue with key


i create a XML file using PHP

$xml=new SimpleXMLElement('<config/>');
$xml->addAttribute("xmlns","http://www.toto.com/tot_config_20110606");
$xml->addAttribute("xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance");
$xml->addAttribute("xsi:schemaLocation","http://www.toto.com/tot_config_20110606 config.xsd"); 

   //some childrens...

file_put_contents($filename, $xml->asXML() , LOCK_EX);

the result is a correct XML file but i have a problem with the attributes

the result is:

<config xmlns="http://www.toto.com/tot_config_20110606" xsi="http://www.w3.org/2001/XMLSchema-instance" schemaLocation="http://www.toto.com/tot_config_20110606 config.xsd">
   //...
</config>

Does someone can explain me how to keep the entire key ?

but i need this result with the first part of the attributes:

<config  xmlns="http://www.toto.com/tot_config_20110606" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.toto.com/tot_config_20110606 config.xsd">
   //...
</config>

Solution

  • Try the suggestion by one p.servus made here and add the parent schema's URL as a third parameter for addAttribute():

    $xml = new SimpleXMLElement("<config></config>");
    $xml->addAttribute("xmlns","http://www.toto.com/tot_config_20110606");
    /***** Update: the following line must be deleted****/
    // $xml->addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance", "http://www.toto.com/tot_config_20110606"); 
    $xml->addAttribute("xsi:schemaLocation", "http://www.toto.com/tot_config_20110606 config.xsd", "http://www.w3.org/2001/XMLSchema-instance"); 
    echo $xml->asXml();