2013-05-14 30 views
0

這兩條線下方目前的XML文檔中起作用,產生2個值:如何添加「ID」屬性,一個PHP的SimpleXML文檔中exsisting元素值

if (isset($images[0]->fname)) { $image1 = $theimgpath.'/'.$images[0]->fname; } else { $image1 = ''; } 
    if (isset($images[1]->fname)) { $image2 = $theimgpath.'/'.$images[1]->fname; } else { $image2 = ''; } 


$image1  current value working = url within xml document require assignment to <image id="1"> 
$image2   current value = url working url within xml document require assignment to <image id="2"> 
$output .= "<url>".$image1."</url>\n";   example of current working value 

期望中的結果上面的工作中的代碼片段目前下同XmlDocument的工作:

`$output .= "<property>\n"; 

$id = $xml["id"];  
$id = $xml->image['id']; 

$output .= $string = <<<XML 

<images> 
<image id="1"><url>id」1」</url></image> 
<image id="2"><url>id」2」</url></image> 
</images> 
XML; 
    $output .= "</property>"; 
} 
$output .= "</root>";` 

回答

0

的SimpleXML庫有方法addAttribute

$image1->addAttribute('id', '1'); 
    $image2->addAttribute('id', '2'); 

但我建議使用的DomDocument使用XML是更強大的


這是你需要什麼

<?php 
    $xml = <<<XML 
<images> 
    <image><url>id"1"</url></image> 
    <image><url>id"2"</url></image> 
</images> 
XML; 
    $images = simplexml_load_string($xml); 
    $images->image[0]->addAttribute('id',1); 
    $images->image[1]->addAttribute('id',2); 
    echo $images->asXML(); 
?> 
+0

Agrest @謝謝您的答覆工作示例但這不起作用並殺死xml文檔輸出:-(和DomDoc不是一個選項:-( – cybernaut 2013-05-14 09:20:57

+0

實例的哪個類是$ image1?你的意思是「殺死XML文件......」文件如何看待addAttribute?執行腳本時有任何警告/錯誤apears? – Agrest 2013-05-14 10:26:53

+0

Agrest @再次感謝,$ image1是一個網址,我使用Dreamweaver CS5.5創建帶有$ image1-> addAttribute('id','1')的PHP/xml;插入此代碼或代碼提示時沒有錯誤,問題在於當我發佈文檔並在瀏覽器中查看它的空白文檔(包含饋送行)時:-(許多感謝 – cybernaut 2013-05-14 13:05:24

相關問題