2016-03-08 116 views
1

我試圖用basename獲得從圖像路徑的文件名和回聲它的標題標籤內,但我不能讓它的工作,因爲我echoeing的來自函數文件的圖像路徑。獲取文件名

什麼我想現在要做的(在product.php):

$path = ProductBekijkPlaatje($contenti[0]['images']); 

$basename = basename($path); 

echo $basename; 

但是,這打破了功能,只相呼應的文件路徑,而實際的圖像丟失。

這是我打電話(在functions.php中)功能:

function ProductBekijkPlaatje($plaatje) { 

    $path = $img->image_intro; 

    $basename = basename($path); 

    $img = json_decode($plaatje); 

    if ($img->image_intro == '') { 
     $image = '<img src="images/no-img.jpg" alt="">'; 
    } else { 

     $image = '<img class="shorterimageimg" title="'.$basename.'" src="cms/'.$img->image_intro.'" alt="'.$img->image_intro_alt.'" >'; 

    } 
    return $image; 

} 

我還試圖表明在函數內部的標題圖像名稱,但這不工作要麼。我究竟做錯了什麼?

+1

你的函數沒有返回路徑,它返回一個完整的html img標籤。基地名稱應該如何在那裏工作? –

+0

@GeraldSchneider你說得對。我怎樣才能獲得圖像路徑? – twan

+0

$普拉傑似乎是一個對象數組,我懷疑你的圖像路徑在那裏定義。執行*的print_r($普拉傑); *和它應該轉儲對象的名稱和它們的值。其中之一應該是文件/路徑。 – 2016-03-08 10:38:42

回答

2

因爲您嘗試做json_decode()之前訪問該對象的屬性不會在你的函數工作:

$path = $img->image_intro;  // $img doesn't exist here 
$basename = basename($path); 
$img = json_decode($plaatje); // here $img is created 

只需推動json_decode()到前面:

$img = json_decode($plaatje); 
$path = $img->image_intro; 
$basename = basename($path); 

現在,你可以修改你的函數返回不同信息的數組:

function ProductBekijkPlaatje($plaatje) { 
    $img = json_decode($plaatje); 
    $return = array(); 
    $return['path'] = $img->image_intro; 
    $return['basename'] = basename($return['path']); 
    if ($img->image_intro == '') { 
     $return['image'] = '<img src="images/no-img.jpg" alt="">'; 
    } else { 
     $return['image'] = '<img class="shorterimageimg" title="'.$return['basename'].'" src="cms/'.$img->image_intro.'" alt="'.$img->image_intro_alt.'" >'; 
    } 
    return $return; 
} 

然後你可以稍後使用這個數組:

$image = ProductBekijkPlaatje($contenti[0]['images']); 
echo $image['image']; // contains the html output 
echo $image['basename']; // contains the basename only 
+0

太棒了,謝謝。我只需要將json_decode移動到前面。現在它可以工作。 – twan