【问题标题】:php DOMDocument find class extract id valuephp DOMDocument 查找类提取id值
【发布时间】:2012-12-23 12:11:40
【问题描述】:

我有这个来自 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 做

我跟着步骤从 Getting DOM elements by classname

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

但我不知道如何提取 ID

【问题讨论】:

  • 所以您要提取文档中不存在的id
  • "所以我想用 domdocument 来做" 所以...你试过什么?
  • 我试过这个stackoverflow.com/questions/6366351/… 没有获取id的参考
  • 你只需要遍历$nodes(你可以用foreach)和getAttribute('id')——你已经完成了99%!

标签: php class element extract domdocument


【解决方案1】:

正如 Dave 已经提到的,你离我们并不遥远:

$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 也会匹配。如果这不是您想要的,您可以轻松地恢复该更改。

【讨论】:

    猜你喜欢
    • 2018-03-22
    • 2012-12-20
    • 2011-01-19
    • 2015-10-13
    • 1970-01-01
    • 2020-07-22
    • 2019-03-08
    • 2019-04-08
    • 2023-04-02
    相关资源
    最近更新 更多