沃梦达 / 编程问答 / php问题 / 正文

调用未定义的方法 DOMDocument::getElementsByClassName(

Call to undefined method DOMDocument::getElementsByClassName()(调用未定义的方法 DOMDocument::getElementsByClassName())

本文介绍了调用未定义的方法 DOMDocument::getElementsByClassName()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从以下 img 标签中获取 alt 标签...

<a href="/Electronic-Deals/b/ref=amb_link_185249707_2?ie=UTF8&amp;node=4192584031&amp;pf_rd_m=A1VBAL9TL5WCBF&amp;pf_rd_s=center-amp_rd_s=center-amp_amp_pZ12&amp;node=4192584031&amp;pf_rd_s=center-amp_amp;JfZM;pf_rd_t=701&amp;pf_rd_p=736512207&amp;pf_rd_i=20"><img src="http://g-ecx.images-amazon.com/images/G/31/rcx-events/cat-navs-electronics1._V335880105_.png" alt="Electronics" border="0"高度=140"宽度=170"></a>

为此,我尝试了以下代码...

$dom = new DOMDocument();@$dom->loadHTML($html2);foreach($dom->getElementsByClassName("localImage") as $tr) {$name = '';foreach($tr->getElementsByTagName('img') as $i){$name = $i->getAttribute('alt');}回声 $name;

但是我收到以下错误...

调用未定义的方法 DOMDocument::getElementsByClassName()

任何人都可以帮助我哪里出错了...因为我之前尝试过这种代码模式,但之前从未遇到过这样的问题.

解决方案

Class DOMDocument 不包含方法 getElementsByClassName
使用 xpath

$xpath = new DOMXpath($dom);$xpath->query('//div[contains(@class, "localImage")]');//DOMNodeList 实例

I am trying to fetch the alt tag from the following img tag...

<div class="localImage">

    <a href="/Electronic-Deals/b/ref=amb_link_185249707_2?ie=UTF8&amp;node=4192584031&amp;pf_rd_m=A1VBAL9TL5WCBF&amp;pf_rd_s=center-new-12&amp;pf_rd_r=07C4YQ4KZ15MZJQBT2PD&amp;pf_rd_t=701&amp;pf_rd_p=736512207&amp;pf_rd_i=20">

    <img src="http://g-ecx.images-amazon.com/images/G/31/rcx-events/cat-navs-electronics1._V335880105_.png" alt="Electronics" border="0" height="140" width="170"></a>

    </div>

For this I have tried the following code...

$dom = new DOMDocument();

@$dom->loadHTML($html2);

  foreach($dom->getElementsByClassName("localImage") as $tr) {

$name = '';

foreach($tr->getElementsByTagName('img') as $i)
{
$name = $i->getAttribute('alt');
}
echo $name;

But am getting the following error...

Call to undefined method DOMDocument::getElementsByClassName()

Can anyone please help me where am getting it wrong...as I have tried this code pattern earlier but never faced such issue earlier.

解决方案

Class DOMDocument does not contains method getElementsByClassName
Use xpath

$xpath = new DOMXpath($dom);
$xpath->query('//div[contains(@class, "localImage")]'); //instance of DOMNodeList

这篇关于调用未定义的方法 DOMDocument::getElementsByClassName()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:调用未定义的方法 DOMDocument::getElementsByClassName(

基础教程推荐