<?php
/*------------------------------*/
/*
Titre : Classe pour générer des fichiers XML
Auteur : erwan
Date édition : 07 Fev 2010
Date mise a jour : 22 Oct 2019
Rapport de la maj:
- fonctionnement du code vérifié
Date mise a jour : 03 Mars 2026
Rapport de la maj:
- fonctionnement du code vérifié
- refactoring du code en PHP 8
*/
/*------------------------------*/
class XML
{
private string $head = '';
private string $key;
private string $value;
/** @var array<string, string> */
private array $attributs;
/** @var XML[] */
private array $tree = [];
public function __construct(string $key, string $value = '', array
$attributs = [])
{
$this->value = $value;
$this->attributs = $attributs;
}
public function setHead(string $head): void
{
$this->head = $head;
}
public function addNode(XML $node): void
{
$this->tree[] = $node;
}
public function addAttribut(string $key, string $value): void
{
$this->attributs[$key] = $value;
}
public function __toString(): string
{
$text = $this->head !== '' ? $this->head . "\n" : '';
$text .= '<' . $this->key;
foreach ($this->attributs as $attrKey => $attrValue) {
// Sécurité minimale contre les injections dans les attributs
'UTF-8');
$text .= ' ' . $attrKey . '="' . $attrValue . '"';
}
$text .= '>';
// Contenu texte uniquement s'il existe
if ($this->value !== '') {
, 'UTF-8') . "\n";
}
// Enfants
foreach ($this->tree as $node) {
$text .= (string)$node;
}
$text .= '</' . $this->key . '>' . "\n";
// Nettoyage des doubles (ou plus) sauts de ligne
return $text;
}
/**
* Méthode magique pour ajouter des nœuds facilement :
* $contact->addNom('Dupond');
* $contact->addAdresse('12 rue...', ['type' => 'principale']);
*/
public function __call(string $name, array $arguments)
{
$key = substr($name, 3); // nom ? Nom ? nom
$value = $arguments[0] ?? '';
$attributs = $arguments[1] ?? [];
$value = (string)$value;
}
$child = new self($key, $value, $attributs);
$this->addNode($child);
return $child;
// ? bonus : on retourne l'enfant créé (chaînage possible)
}
return null;
}
}
?>