【问题标题】:Problem to get content from html string variable in php从 php 中的 html 字符串变量获取内容的问题
【发布时间】:2018-10-21 09:49:47
【问题描述】:

我有这个代码:

     $doc = new \DOMDocument();
  $doc->loadHTML($content);


    $links = [];
  $container = $doc->getElementById("content");
  $arr = $container->getElementsByTagName("a");
  foreach($arr as $item) {
    $href =  $item->getAttribute("href");
    $title =  $item->getAttribute("title");
    $links[] = [
      'href' => $href,
      'title' => $title
    ];
  }
  for($i = 0, $l = count($links); $i < $l; ++$i) {
  echo $links[$i]['title'].' '.$links[$i]['href'].'<br />';
}

html结构是这样的:

<div class="post-content right-col">
                    <a title="" href="https://www.swisscars.pl/samochody/516321/">
                        <img src="https://swisscars.pl/uploads2/180843_0.jpg" alt="" class="thumb alignleft" height="75" width="75"/>
                    </a>
                    <h2 style="line-height:150%;">
                        <a href="https://www.swisscars.pl/samochody/516321/" rel="bookmark"  title="Renault Kangoo II (96&#8217;011 km)">
                            Renault Kangoo II (96&#8217;011 km)                     </a>
                    </h2>
                Do końca aukcji: <span id="countdown100">2018-10-23 14:00:00 GMT+02:00</span><p>DATA ZAKONCZENIA AUKCJI: 2018-10-23 14:00</p>

                </div>

            </div>

我只想从标签女巫属性 rel="bookmark" 中获取值。请帮我解决一下这个。我尝试使用 hasAttribute 函数但不工作。请描述我只能从具有 rel="bookmark" 属性的标签中获得什么内容。 PHP有hasAttribute()函数还是类似这个函数?

感谢您的帮助

【问题讨论】:

  • 我在显示的 html 中找不到任何具有 content id 的元素
  • 在你的循环中使用if ($item-&gt;hasAttribute('rel') &amp;&amp; $item-&gt;getAttribute('rel') == 'bookmark')..

标签: php html-parsing


【解决方案1】:

XPath 可能是一个选项,您可以这样做:

$doc = new \DOMDocument();
$doc->loadHTML($content);

$xpath = new DOMXPath($dom);
$links = $xpath->query('//a[@rel="bookmark"]');

这应该返回一个您可以循环访问的 DOMNodeList。

【讨论】:

    猜你喜欢
    • 2019-11-16
    • 2012-03-24
    • 1970-01-01
    • 1970-01-01
    • 2013-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多