根据类或 id 获取图像的 src 属性 [英] get src attribute of an image based on class or id
问题描述
我想根据类或 id 获取图像中的 src.前任.在 html 页面上有很多 <img src="url">
但只有一个有一个类或 id:如何获得具有特定类或 id 的正确 src 属性?请不要使用正则表达式
I want to get src in image based on class or id.
Ex. On html page there are many <img src="url">
but only one have a class or id:
<img src="url" class="image" or id="image">
How to get right src attribute wich have a specific class or id?
Pls regex not dom
我将向您解释为什么我不想使用 dom 或其他库,因为我从其他站点获取 html 页面,该页面不允许 fopen 或 _file_get_contents 或 DOM 但只有 Curl 可以这样做.我当然有理由不使用像 simplehtmldom 这样的库,因为有时无法获取远程 html 页面,我应该自己制作一些脚本.
I gonna explain you why I dont want to use dom or other libraries because I'm getting a html page from an other site which not allow fopen or _file_get_contents or DOM but only Curl could do this. Sure I have a reason why I not use these libraries like simplehtmldom because sometimes is impossible to get remote html page and I should make by myself some scripts.
推荐答案
你说你不想使用 DOM 库,因为你需要使用 cURL.没关系——DOMDocument
和 simple_xml_load_string
都采用字符串参数.因此,您可以从 cURL 获取字符串并将其加载到您的 DOM 库中.
You say that you don't want to use DOM libraries because you need to use cURL. That's fine -- DOMDocument
and simple_xml_load_string
both take string arguments. So you can get your string from cURL and load it into your DOM library.
例如:
$html = curl_exec($ch); // assuming CURLOPT_RETURNTRANSFER
$dom = new DOMDocument;
$dom->loadHTML($html); // load the string from cURL into the DOMDocument object
// using an ID
$el = $dom->getElementById('image');
// using a class
$xpath = new DOMXPath($dom);
$els = $xpath->query('//img[@class="image"]');
$el = $els->item(0);
$src = $el->getAttribute('src');
这篇关于根据类或 id 获取图像的 src 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!