2017-05-01 53 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属性的更好方法。

相关问题