使用 PHP 简单 HTML DOM 从 "data-srcset" 属性中仅获取一个 URL

Getting only ONE URL from a "data-srcset" attribute with PHP Simple HTML DOM

我正在尝试从外部网站抓取图像 URL,用作我自己网站上图像元素中的 src 属性。

问题是,在外部网站上,图像 URL 嵌套在 picture 元素,在 source 元素中,然后在 "data-srcset" 属性中以不同的大小对其进行迭代。示例:

<picture><source data-srcset="https://imageurl.com 640w, https://imageurl.com 720w, https://imageurl.com 860w"></picture>

我可以使用 PHP 简单 HTML DOM 的 find() 定位特定元素并将其存储在变量中。此变量称为 $imageselector。我可以通过为 data-srcset 创建一个变量来进一步定位实际属性:

$srcset = 'data-srcset';

我的最终输出如下所示:

<?php echo $imageselector->$srcset; ?>

然而,这试图打印属性内的所有内容(当然),这对我来说不是很有用。

有没有人知道如何只获取属性中的第一个 URL?

(添加最大长度也没什么用,因为 URL 的长度随时可能改变)

您可以采用 $imageselector->$srcset,将其内容拆分为一个数组并根据需要进行过滤。

$longString = $imageselector->$srcset;
$pics = explode(",", $longString)

现在你有一个包含诸如 "https://imageurl.com 640w" 之类的数组,所以现在你可以以 [1] 为例。

$toUse = explode(" ", $pics[1]);
$toUse = $toUse[0]; //to get the useful part of the item

或者,您也可以预过滤整个数组

function getLink($string) {
    return substr($string, 0, strpos($string, " "));
}
//Once you already have the exploded string
$pics = array_filter($pics, "getLink");