2016-12-04 60 views
-1

我需要您的幫助。關於如何從給定的XML數據更改img src有點困惑。使用PHP更新XML屬性,但結果爲「無法在寫入上下文中使用方法返回值」

錯誤返回:

Can't use method return value in write context 

如何解決這個問題呢?任何幫助將不勝感激。謝謝!祝你今天愉快!

<?php 

$question_data = '<p>My questions here....</p><p>&nbsp;</p><p><img class="img-responsive" src="/uploads/images/questions/93_20161017102613.jpg" style="max-height:400px;" /></p>'; 

$xml = new DOMDocument(); 
$xml->loadHTML($question_data, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); 


echo '<pre>'; 

//Initial Dom 

//Find only image and convert url 

//Process to convert url 
$imgNodes = $xml->getElementsByTagName('img'); 


echo '<br/>'; 
$arr_image_file_names = []; 

for ($i = $imgNodes->length - 1; $i >= 0; $i--) { 
    $imgNode = $imgNodes->item($i); 
    $image_file_names = pathinfo($imgNode->getAttribute('src'), PATHINFO_BASENAME); 

    if(!empty($image_file_names)): 
    // Replace with new src 

    $imgNode->getAttribute('src') = 'http://myurl/qst/def/img/v1/'.$image_file_names; 

    endif; 
} 

echo '<br/>'; 
echo htmlentities($xml->saveHTML()); 

//Update into new array 


//Convert back to DOM 


echo '</pre>'; 


?> 

回答

1

您應該使用,而不是setAttribute function

$imgNode->setAttribute('src', 'http://myurl/qst/def/img/v1/'.$image_file_names); 

getAttribute函數的結果是一個字符串(而不是變量),你可以不分配新值的字符串(或在這種情況下 - 函數的返回值)。

+0

謝謝!你救我的日子! – Nere

+0

你能告訴我如何添加屬性?是相同的: '$ imgNode-> addAtribute('style','max-width:100%');'? – Nere

+1

不,它與'setAttribute'相同,'setAttribute'如果不存在則添加屬性。 – Dekel

相關問題