使用 DOMdocument() 方法通过 ClassName 获取元素 [英] Get Element by ClassName with DOMdocument() Method

查看:24
本文介绍了使用 DOMdocument() 方法通过 ClassName 获取元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我想要实现的目标:检索页面上的所有产品并将它们放入一个数组中.这是我正在使用的代码:

Here is what I am trying to achieve : retrieve all products on a page and put them into an array. Here is the code I am using :

$page2 = curl_exec($ch);
$doc = new DOMDocument();
@$doc->loadHTML($page2);
$nodes = $doc->getElementsByTagName('title');
$noders = $doc->getElementsByClassName('productImage');
$title = $nodes->item(0)->nodeValue;
$product = $noders->item(0)->imageObject.src;

它适用于 $title 但 不适用于产品.有关信息,在 HTML 代码中,img 标记如下所示:

It works for the $title but not for the product. For info, in the HTML code the img tag looks like this :

<img alt="" class="productImage" data-altimages="" src="xxxx">

我一直在看这个(PHP DOMDocument 如何获取元素?) 但我仍然不明白如何让它工作.

I have been looking at this (PHP DOMDocument how to get element?) but I still don't understand how to make it work.

PS:我收到此错误:

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

推荐答案

我最终使用了以下解决方案:

I finally used the following solution :

    $classname="blockProduct";
    $finder = new DomXPath($doc);
    $spaner = $finder->query("//*[contains(@class, '$classname')]");

这篇关于使用 DOMdocument() 方法通过 ClassName 获取元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆