我想用PHP编辑一个XML文件


I want to edit an XML file using PHP

这是我的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文件中,但要按递增顺序添加。因此,在添加此时间之前,我必须将该时间与其他时间进行比较,然后将其添加到适当的位置。

有人能建议我怎么做吗。一个示例代码将非常有用。

正如Gordon的回答中所建议的,我会将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");