views:

9

answers:

1

It works properly in the way that it breaks up the comma-separated values into an array (with explode), but when it adds the child nodes, they show up after the closing root tag. What I'm trying to do here is replace the <Genres>Adventure,Crime,Action</Genres> with

<Genre>Adventure</Genre>
<Genre>Crime</Genre>
<Genre>Action</Genre>

A simplified XML source:

<?xml version="1.0" encoding="UTF-8"?>
<root><Product><Genres>Adventure,Crime,Action</Genres></Product></root>

<Genre>Adventure</Genre>
<Genre>Crime</Genre>
<Genre>Action</Genre>

My function:

global $genreArray;
$genres = explode(",",$genreArray->nodeValue);

 foreach ($genres as $genre) {
 $node = $XmlDoc->createElement('Genre', $genre);
 $XmlDoc->appendChild($node);
 }

}

Thanks for any help, I've been working on this for days now lol ;)

A: 

The answer was to add a function "insertNewChild" and use it thusly:

    //Convert Genres CSV into individual Genre nodes

global $genreArray;
if (substr_count($genreArray->nodeValue, ',') > 0) 
    {
    $genres = explode(",",htmlspecialchars($genreArray->nodeValue));
    $genreArray->nodeValue = "";
    $allgenres = $XmlDoc->getElementsByTagName('Genres');
    $parent = $allgenres->item(0);
        foreach ($genres as $genre) 
        {
        $newnode = $XmlDoc->createElement('Genre', $genre);
        insertNewChild($parent,$newnode);
        }
    } 
else 
{
$genre = htmlspecialchars($genreArray->nodeValue);
$genreArray->nodeValue = "";
$allgenres = $XmlDoc->getElementsByTagName('Genres');
$parent = $allgenres->item(0);
$newnode = $XmlDoc->createElement('Genre', $genre);
insertNewChild($parent,$newnode);
}

and the insertNewChild function :

function insertNewChild($currentNode, $node)
{
   $currentNode->insertBefore($node, $currentNode->firstChild);   
}
Chris