开发者

How do I change this function to add the child nodes into the //root/Product/Genres node instead of adding to the end of the file (i.e. after </root>

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><Pro开发者_如何学Cduct><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 ;)


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);   
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜