2013-03-22 113 views
0

我在嘗試更改XML值,然後將其保存爲XML。 當我更改沒有命名空間的元素時工作正常。問題是,當我想要改變的值在一個名字空間中時,我可以找到並打印出來,但任何更改都會被忽略;像這樣:如何使用simplexml更改名稱空間元素的值?

$ns = $xmlsingle->children('mynamespace'); 
foreach ($ns as $myelement) 
{ 
    echo "my element is: [$myelement]"; 
    //I can change it: 
    $myelement = "something else"; 
    echo "my element is now: [$myelement]"; //yay, value is changed! 
} 
//GREAT! 
//But when I save the XML back, the value is not changed... apparently the children method creates a new object; not a link to the existing object 
//So if I copy/paste the code above, I have the original value, not the changed value 
$ns2 = $xmlsingle->children('mynamespace'); 
foreach ($ns2 as $myelement) 
{ 
    echo "my element is UNCHANGED! [$myelement]"; 
} 
//So my change's not done when I save the XML. 
$xmlsingle->asXML(); //This XML is exacly the same as the original XML, without changes to the namespaced elements. 

**請忽略可能無法編譯任何愚蠢的錯誤,我重新輸入從我的原代碼的文本,否則會過大;代碼起作用,只要NAMESPACED元素的值在我將其放回到XML時保持不變。

我不是PHP專家,我不知道如何以任何其他方式訪問命名空間元素......我如何更改這些值?我到處搜索,但只找到如何讀取值的說明。

+0

顯示您的XML,請 – michi 2013-03-23 00:05:45

回答

1

嘗試這樣:

$xml = ' 
<example xmlns:foo="bar"> 
    <foo:a>Apple</foo:a> 
    <foo:b>Banana</foo:b> 
    <c>Cherry</c> 
</example>'; 

$xmlsingle = new \SimpleXMLElement($xml); 
echo "<pre>\n\n"; 
echo $xmlsingle->asXML(); 
echo "\n\n"; 

$ns = $xmlsingle->children('bar'); 
foreach ($ns as $i => $myelement){ 
    echo "my element is: [$myelement] "; 

    //$myelement = "something else"; // <-- OLD 
    $ns->$i = 'something else'; // <-- NEW 

    echo "my element is now: [$myelement]"; //yay, value is changed! 
    echo "\n"; 
} 
echo "\n\n"; 
echo $xmlsingle->asXML(); 
echo "\n</pre>"; 

和結果應該是:

 

    
    
     Apple 
     Banana 
     Cherry 
    

    my element is: [Apple] my element is now: [something else] 
    my element is: [Banana] my element is now: [something else] 

    
    
     something else 
     something else 
     Cherry 
    

希望這有助於。

+0

偉大!有效;非常感謝! :-) – LFLFM 2013-03-25 20:24:08