[XML] Problème indentation XML
Bonjour,
Dans le but de gérer la configuration de mon site et ses Logs j'ai créer une classe XMLManager dont la method static "append" a un comportement inattendu et inexplicable : l'indentation fonctionne lorsque le fichier n'existe pas, mais pas lorsque celui-ci existe déjà.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| <?php namespace kernel\XMLManager;
class XMLManager
{
static public function append($url, $array)
{
$dir = substr($url, 0, strrpos($url, "/"));
if(!file_exists($url))
{
if(!is_writable($dir))
{
\kernel\Error\report("Error: \kernel\XMLManager\XMLManager::read(\$url = ".$url.") : le fichier XML ne peut pas être créer !",
\kernel\Error\IMPORTANT);
}
$xml = new \SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><root></root>');
}
else
{
if(!is_readable($url))
{
\kernel\Error\report("Error: \kernel\XML\read(\$url = ".$url.") : le fichier ne peut pas être utilisé en écriture !",
\kernel\Error\IMPORTANT);
}
if(!is_writable($url))
{
\kernel\Error\report("Error: \kernel\XML\read(\$url = ".$url.") : le fichier ne peut pas être lu !",
\kernel\Error\IMPORTANT);
}
$xml = simplexml_load_file($url);
}
self::array_to_xml($array, $xml);
$dom = dom_import_simplexml($xml)->ownerDocument;
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->save($url);
}
static private function array_to_xml($array, $xml)
{
foreach($array as $key => $value)
{
if(is_array($value))
{
if(!is_numeric($key))
{
$subnode = $xml->addChild($key);
self::array_to_xml($value, $subnode);
}
else
{
self::array_to_xml($value, $xml);
}
}
else
{
if(is_numeric($key))
{
$xml->addChild("n".$key,$value);
}
else
{
$xml->addChild($key, $value);
}
}
}
}
}
?> |
fichier test.php :
Code:
1 2 3 4 5 6 7 8 9 10 11
| <?php
require_once("kernel/XMLManager/XMLManager.php");
$test = array("test1" => "value",
"test2" => "value",
"array" => array("test3" => "value",
"test4" => "value",
"test5" => "value"),
"test6" => "truc"));
kernel\XMLManager\XMLManager::append(__DIR__."/Logs/test.xml", $test);
kernel\XMLManager\XMLManager::append(__DIR__."/Logs/test.xml", $test);
?> |
et le résultat, en admettant que le fichier "test.xml" n'existe pas enore:
Code:
1 2 3 4 5 6 7 8 9 10 11
| <?xml version="1.0" encoding="utf-8"?>
<root>
<test1>value</test1>
<test2>value</test2>
<array>
<test3>value</test3>
<test4>value</test4>
<test5>value</test5>
</array>
<test6>truc</test6>
<test1>value</test1><test2>value</test2><array><test3>value</test3><test4>value</test4><test5>value</test5></array><test6>truc</test6></root> |
Merci d'avance pour votre aide.