Friday, July 17, 2009

simplexml xpath php, select insert update delete

<?php
$data ='<?xml version="1.0" encoding="utf-8"?>
<infos>
<info time="1247640983" count="0" detail="will be updated" uid="1" path="/var/www/user/1/codjng.avi">MOT</info>
<info time="1247640983" count="0" detail="will be updated" uid="2" path="/var/www/user/2/codjng.zip">HAI</info>
<info time="1247640983" count="0" detail="will be updated" uid="3" path="/var/www/user/3/codjng-3.txt" />
</infos>';

$xml = simplexml_load_string($data);
// select
$elements = $xml->xpath("/infos/info");
foreach ($elements as $ele) {
echo $ele[0];
}
echo "<pre>" . htmlspecialchars($xml->asXML()) . "</pre><hr/>";

// delete first element
unset($elements[0][0]);
echo "<pre>" . htmlspecialchars($xml->asXML()) . "</pre><hr/>";

// update second element
$elements[1]["path"] = "/var/www/user/2/codjng-modify.zip";
echo "<pre>" . htmlspecialchars($xml->asXML()) . "</pre>";

// insert element
$ele = $xml->addChild("info");
$ele->addAttribute("count", "1000");
$ele[0] = "bla bla codjng";
echo "<pre>" . htmlspecialchars($xml->asXML()) . "</pre>";
?>

1 comment:

Anonymous said...

$obj = simplexml_load_file('C:\Program Files\Yahoo!\Messenger\Media\Smileys\emoticons.xml');
$result = $obj->xpath('/emoticons/emoticon');
while(list( , $node) = each($result)) {
$arr = $node->xpath('shortcuts/shortcut');

$a = $node->attributes();

echo '"' . addcslashes($arr[0],'"\\') . '": "' . $a['fname'] . ".gif\"\n";
}

Post a Comment