/*---------------------------------------------------------------*/
|
/*
|
Titre : Classe pour générer des fichiers XML
|
|
URL : https://phpsources.net/code_s.php?id=561
|
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->key = strtolower($key);
|
$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
|
$attrValue = htmlspecialchars($attrValue, ENT_QUOTES | ENT_XML1,
|
'UTF-8');
|
$text .= ' ' . $attrKey . '="' . $attrValue . '"';
|
}
|
|
$text .= '>';
|
|
// Contenu texte uniquement s'il existe
|
if ($this->value !== '') {
|
$text .= "\n" . htmlspecialchars($this->value, ENT_QUOTES | ENT_XML1
|
, 'UTF-8') . "\n";
|
}
|
|
// Enfants
|
foreach ($this->tree as $node) {
|
$text .= (string)$node;
|
}
|
|
$text .= '</' . $this->key . '>' . "\n";
|
|
// Nettoyage des doubles (ou plus) sauts de ligne
|
$text = preg_replace('/\n{2,}/', "\n", $text);
|
|
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)
|
{
|
if (str_starts_with($name, 'add')) {
|
$key = substr($name, 3); // nom ? Nom ? nom
|
$key = strtolower($key);
|
|
$value = $arguments[0] ?? '';
|
$attributs = $arguments[1] ?? [];
|
|
if (!is_string($value)) {
|
$value = (string)$value;
|
}
|
|
$child = new self($key, $value, $attributs);
|
$this->addNode($child);
|
|
return $child;
|
// ? bonus : on retourne l'enfant créé (chaînage possible)
|
}
|
|
trigger_error("Méthode $name inexistante", E_USER_WARNING);
|
return null;
|
}
|
}
|
| ?> |