PHP + XML - how to rename and delete XML elements

2019-07-09 03:04发布

问题:

I've had some success due to the help of StackOverflow community to modify a complex XML source for use with jsTree. However now that I have data that is usable, it is only so if i manually edit the XML to do the following :

  1. Rename all <user> tags to <item>
  2. Remove some elements before the first <user> tag
  3. insert an 'encoding=UTF-8' into the XML opener
  4. and lastly modify the <response> (opening XML tag) to <root>

XML File Example : SampleXML

I have read and read through so many pages on here and google but cannot find a method to achieve the above items.

Point (2) I have found out that by loading it via SimpleXML and using UNSET i can delete the portions I do not require, however I am still having troubles with the rest.

I thought I could perhaps modify the source with SimpleXML (that I am more familiar with) and then continue to modify the code via the help I had been provided before.

<?php
$s = file_get_contents('http://www.fluffyduck.com.au/sampleXML.xml');
$doc1 = simplexml_load_string($s);

unset($doc1->row);
unset($doc1->display);

#$moo = $doc1->user;
echo '<textarea>';
echo $doc1->asXML();
echo '</textarea>';

$doc = new DOMDocument();
$doc->loadXML($doc1);

$users = $doc->getElementsByTagName("user");
foreach ($users as $user)
{
    if ($user->hasAttributes())
    {
        // create content node
        $content = $user->appendChild($doc->createElement("content"));
        // transform attributes into content elements
        for ($i = 0; $i < $user->attributes->length; $i++)
        {
            $attr = $user->attributes->item($i);
            if (strtolower($attr->name) != "id")
            {
                if ($user->removeAttribute($attr->name))
                {
                        if($attr->name == "username") {
                                $content->appendChild($doc->createElement('name', $attr->value));
                        } else {
                            $content->appendChild($doc->createElement($attr->name, $attr->value));
                        }
                    $i--;
                }
            }
        }
    }
}
$doc->saveXML();

header("Content-Type: text/xml");
echo $doc->saveXML();

?>

回答1:

Using recursion, you can create a brand new document based on the input, solving all your points at once:

Code

<?php

$input = file_get_contents('http://www.fluffyduck.com.au/sampleXML.xml');
$inputDoc = new DOMDocument();
$inputDoc->loadXML($input);

$outputDoc = new DOMDocument("1.0", "utf-8");
$outputDoc->appendChild($outputDoc->createElement("root"));

function ConvertUserToItem($outputDoc, $inputNode, $outputNode)
{
    if ($inputNode->hasChildNodes())
    {
        foreach ($inputNode->childNodes as $inputChild)
        {
            if (strtolower($inputChild->nodeName) == "user")
            {
                $outputChild = $outputDoc->createElement("item");
                $outputNode->appendChild($outputChild);
                // read input attributes and convert them to nodes
                if ($inputChild->hasAttributes())
                {
                    $outputContent = $outputDoc->createElement("content");
                    foreach ($inputChild->attributes as $attribute)
                    {
                        if (strtolower($attribute->name) != "id")
                        {
                            $outputContent->appendChild($outputDoc->createElement($attribute->name, $attribute->value));
                        }
                        else
                        {
                            $outputChild->setAttribute($attribute->name, $attribute->value);
                        }
                    }               
                    $outputChild->appendChild($outputContent);
                }
                // recursive call
                ConvertUserToItem($outputDoc, $inputChild, $outputChild);
            }
        }
    }
}

ConvertUserToItem($outputDoc, $inputDoc->documentElement, $outputDoc->documentElement);

header("Content-Type: text/xml; charset=" . $outputDoc->encoding);
echo $outputDoc->saveXML();
?>

Output

<?xml version="1.0" encoding="utf-8"?>
<root>
    <item id="41">
        <content>
            <username>bsmain</username>
            <firstname>Boss</firstname>
            <lastname>MyTest</lastname>
            <fullname>Test Name</fullname>
            <email>lalal@test.com</email>
            <logins>1964</logins>
            <lastseen>11/09/2012</lastseen>
        </content>
        <item id="61">
            <content>
                <username>underling</username>
                <firstname>Under</firstname>
                <lastname>MyTest</lastname>
                <fullname>Test Name</fullname>
                <email>lalal@test.com</email>
                <logins>4</logins>
                <lastseen>08/09/2009</lastseen>
            </content>
        </item>
...