2017-05-01 16 views
0

我正在製作一個Wordpress主題,並且我有一個自定義短代碼。短代碼將一些內容與圖像包裹在一起。短代碼使用DOMDocument提取圖像的src,並使用該網址將其作爲新DIV的背景圖像。PHP DOMDocument操作在本地運行時返回期望值,但當頁面在服務器上運行時返回空值

下面是相關代碼:

//find image src 
$html = do_shortcode($content); 

$doc = new DOMDocument(); 
libxml_use_internal_errors(true); 
$doc->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); 
$xpath = new DOMXPath($doc); 
$src = $xpath->evaluate("string(//img/@src)"); # "/images/image.jpg" 

echo '<script>console.log('.'"Source: '.$src.'");</script>'; 

$overlay_html = ''; 
foreach($xpath->evaluate("//*[contains(@class, 'sp-img-overlay')]") as $childNode) { 
    $overlay_html .= $doc->saveHtml($childNode); 
} 

//removes empty p tags from content 
$content = do_shortcode($content); 
$content = force_balance_tags($content); 
$content = preg_replace('#<p>\s*+(<br\s*/*>)?\s*</p>#i', '', $content); 

//removes the actual images and captions 
$just_text = $content; 
$just_text = preg_replace('#(<figure.*?>).*?(</figure>)#', '', $just_text); 
$just_text = preg_replace("/<img[^>]+\>/i", "", $just_text); 


//build output 
//make src captured earlier the background image. 
$output = '<div class="section-pairing full-bleed-mobile">'; 
    $output .= '<div class="section-pairing-img full-bleed-mobile '.$img_side.' '.$values['mobile_img_size'] .'" style=" background-image:url('. $src .')">'; 
     $output .= $overlay_html; 
    $output .= '</div>'; 

    $output .= '<div class="section-pairing-text '.$text_side.'">'; 
     $output .= $just_text; 
    $output .= "</div>"; 
$output .= "</div>"; 


return $output; 

當我在我的本地開發環境中運行這個,那個控制檯日誌。 。 。

echo '<script>console.log('.'"Source: '.$src.'");</script>'; 

。 。 。返回圖像的正確路徑,並且短代碼按預期工作。 但是,當我遷移到服務器,頁面上的其他一切工作正常,但這個短代碼不起作用,並且該控制檯日誌返回「源:」沒有網址,也沒有圖像。

我是新開發的Web開發人員,對於使用DOMDocument真的很陌生,所以如何使這項工作的任何建議,將不勝感激。

回答

0

嘿大家我找到了解決方案。

//find image src 
$html = do_shortcode($content); 

$doc = new DOMDocument(); 
libxml_use_internal_errors(true); 
$doc->loadHTML($html); 
$allImages = $doc->getElementsByTagName('img'); 
$imgL = $allImages->length; 
$bgimg = $allImages->item(0); 
$src = $bgimg->getAttribute('src'); 

的關鍵似乎丟棄|從loadHTML命令 「LIBXML_HTML_NOIMPLIED LIBXML_HTML_NODEFDTD」。我曾經解決過我之前遇到的一些問題,但現在沒有他們,一切正常。

我還發現我認爲是獲取src屬性的更好方法。

相關問題