2010-04-27 134 views
2

我有一個看起來像這樣的XML文件。修改XML屬性PHP DOM

<collections id="my collections"> 
<category id="my category"> 
    <record id="my record"> 
    <title>Some Info</title> 
    </record> 
</category> 
</collections> 

我在找一個新的屬性,使用PHP DOM和Xpath替換上述XML文件中的任何屬性。 任何幫助,高度讚賞

回答

5

不知道你想要做的完全是,但總體思路是:


這裏,例如,您可以使用一些這樣的事:

$str = <<<XML 
    <collections id="My Collections"> 
    <category id="my category"> 
     <record id="my record"> 
     <title>Some Info</title> 
     </record> 
    </category> 
    </collections> 
XML; 

$dom = new DOMDocument(); 
$dom->loadXML($str); 

$xpath = new DOMXPath($dom); 
$elements = $xpath->query('//record[@id="my record"]'); 
if ($elements->length >= 1) { 
    $element = $elements->item(0); 
    $element->setAttribute('id', "glop !"); 
} 
echo '<pre>' . htmlspecialchars($dom->saveXML()) . '</pre>'; 


這將替換id屬性my record,這是由它確定的,由「glop !」的節點上,你會得到下面的XML作爲輸出:

<?xml version="1.0"?> 
<collections id="My Collections"> 
    <category id="my category"> 
     <record id="glop !"> 
     <title>Some Info</title> 
     </record> 
    </category> 
    </collections> 
1

Suposing ID =「我的紀錄」是在XML是獨一無二的。辛苦的工作只在xpath表達式中。

$dom = new DomDocument(); 
    $dom->load('test.xml'); 
    $xp = new DomXPath($dom); 
    $res = $xp->query("//*[@id = 'my record']"); 
    $res->item(0)->setAttribute('id','2'); 
    $dom->save('test.xml');