I want to edit an XML file using PHP
This is my XML file.
<body>
<div>
<p time="00:00:08"> </p>
<p time="00:00:10"> </p>
<p time="00:00:13"> </p>
</div>
</body>
Now I want to add time = "00:00:12" to the XML file, but in increasing order. So, before adding this time, I will have to compare the time with other times and then add it at appropriate location.
Can anybody suggest me how to do this. A sample code wo开发者_JAVA百科uld very helpful.
As was suggested in Gordon's answer, I would load the XML file into SimpleXML, append the node and then sort it.
I've commented the code below to explain it step-by-step.
<?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");
精彩评论