简体   繁体   中英

How to convert PHP array to DOM XML nodeList?

I'm looking for a DOM XML function to convert PHP array like this:

<?php
$errors = array("A", "B", "C", "D");
?>

to DOM XML NodeList

<?xml version="1.0" standalone="no"?>
<error>
    <missing>A</missing>
    <missing>B</missing>
    <missing>C</missing>
    <missing>D</missing>
</error>

Thank you very much for your help :)

I tried the following code:

<?php
$basedoc = new DomDocument();
$basedoc->Load("Standard.svg"); //Fichier SVG de base
$baseroot = $basedoc->documentElement; //On prend l'élément racine
$errorgroup = $basedoc->createElement('error'); //On crée le groupe de base
foreach($erreurs as $erreur) {
    $missinggroup = $errorgroup->createElement('missing'); //On crée le groupe de base
    $errorgroup->appendChild($missinggroup);
}
$baseroot->appendChild($errorgroup);
?>

I think this is too simple structure to use DomXML functions. I think you should create simple view template for this XML - it'll look something like that:

<?xml version="1.0" standalone="no"?>
<error>
    <?php foreach ($errors as $error):?>
        <missing><?php echo $error;?></missing>
    <?php endforeach;?>
</error>

The exact template structure of course depends on your framework - in zend it'll be $this->errors instead of $errors for example.

Od use the SimpleXML as sugested by @bassem-ala in first link.

UPDATE

Here's the 'recursive' function to generate XML based on table. Something like that

function generateXMLElement($elements, $rootNode = null, $rootNodeName = 'xml')
{
    if (!$rootNode)
    {
        $rootNode = new SimpleXMLElement('<'.$rootNodeName.'/>');
    }
    foreach ($elements as $key => $val)
    {
        if (is_array($val))
        {
            $childElem = $rootNode->addChild($key);
            generateXMLElement($val, $childElem);
        }
        else
        {
            $childElem = $rootNode->addChild($key, $val);
        }
    }
    return $rootNode;
}

You get the XML using $xml = generateXMLElement($errors, null, 'error'); then you can print it using print($xml->asXML());

You are not not using $erreur anywhere in the creation code so obviously it wont be in the resulting XML. Also, you cannot create an Element from a DOMElement but must create it from the DOMDocument . Your code will give a Fatal Error.

Change

$missinggroup = $errorgroup->createElement('missing');

to

$missinggroup = $basedoc->createElement('missing', $erreur);

and then it will work: http://codepad.org/GmCIBIQW

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM