2

我有这个来自 stagram 的 html:

<div id="photo351321902758808423_176859145" class="photoeach">
    <div class="photoeachinner">
        <div class="left">
            <div class="photowrapper">
                <div class="infomation_box clearfix">
                    <div class="profimage_small">

<div id="photo351295515670923844_176859145" class="photoeach">
    <div class="photoeachinner">
        <div class="left">
            <div class="photowrapper">
                <div class="infomation_box clearfix">

我需要找到类 photoeach 并提取 id 352034826703915686_176859145

我用正则表达式做了,但没有运气,所以我试着用 domdocument

我遵循 通过类名获取 DOM 元素的步骤

$dom = new DomDocument();
$dom->load($filePath);
$finder = new DomXPath($dom);
$classname="photoeach";
$nodes = $finder->query("//*[contains(@class, '$classname')]");

但我无法弄清楚如何提取 ID

4

1 回答 1

4

正如戴夫已经提到的那样,您并没有那么遥远:

$dom = new DomDocument();
$dom->load($filePath);
$finder = new DomXPath($dom);
$classname="photoeach";
$nodes = $finder->query("//*[@class = '$classname']");

foreach ($nodes as $node) {
    echo 'Id: ' , substr($node->getAttribute('id'), 5) , '<br>';
}

演示:http ://codepad.viper-7.com/xEdYLr

请注意,我已将contains类的选择器更改为仅匹配完全匹配,否则photoeachinner也会匹配。如果这不是您想要的,您可以轻松地恢复该更改。

于 2012-12-26T03:28:02.533 回答