我想用PHP编辑XML文件

时间:2011-06-27 10:40:26

标签: php xml

这是我的XML文件。

<body>
   <div>
     <p time="00:00:08"> </p>
     <p time="00:00:10"> </p>
     <p time="00:00:13"> </p>
   </div>
</body>

现在我想将time =“00:00:12”添加到XML文件中,但是按顺序递增。 因此,在添加此时间之前,我必须将时间与其他时间进行比较,然后将其添加到适当的位置。

有人可以建议我怎么做。示例代码非常有用。

1 个答案:

答案 0 :(得分:2)

正如Gordon's answer中所建议的那样,我会将XML文件加载到SimpleXML中,附加节点然后对其进行排序。

我已经评论了下面的代码,一步一步地解释它。

<?php

// Open the XML file
$xml = file_get_contents("captions.xml");
// SimpleXml is an "easy" API to manipulate XML
// A SimpleXmlElement is any element, in this case it will be the <body> 
// element as it is first in the file.
$timestamps = new SimpleXmlElement($xml);

// Add our new time entry to the <div> element inside <body>
$timestamps->div->addChild("p", null);
// Get the index of the last element (the one we just added)
$index = $timestamps->div->p->count()-1;
// Add a time attribute to the element we just added
$e = $timestamps->div->p[$index];
$e->addAttribute("time", "00:00:12");
// Replace it with the new one (with a time attribute)
$timestamps->div->p[$index] = $e;

// Sort the elements by time (I've used bubble sort here as it's in the top of my head)
// Make sure you're setting this here or in php.ini, otherwise we get lots of warnings :)
date_default_timezone_set("Europe/London");

/**
 * The trick here is that SimpleXmlElement returns references for nearly
 * everything. This means that if you say $c = $timestamps->div->p[0], changes
 * you make to $c are made to $timestamps->div->p[0]. It's the same as calling
 * $c =& $timestamps->div->p[0]. We use the keyword clone to avoid this.
 */ 
$dates = $timestamps->div->children();
$swapped = true;
while ($swapped) {
    $swapped = false;
    for ($i = 0; $i < $dates->count() - 1; $i++) {
        $curTime = clone $dates[$i]->attributes()->time;
        $nextTime = clone $dates[$i+1]->attributes()->time;

        // Swap if current is later than next
        if (strtotime($curTime) > strtotime($nextTime)) {
            $dates[$i]->attributes()->time = $nextTime;
            $dates[$i+1]->attributes()->time = $curTime;
            $swapped = true;
            break;
        }
    }
}

// Write back
echo $timestamps->asXml();
//$timestamps->asXml("captions.xml");