简体   繁体   English

PHP Dom使用strpos获得某些href值

[英]PHP Dom Get Certain href Value Using strpos

Could someone please tell me why this ain't working. 有人可以告诉我为什么这不起作用。

I'm trying to get a certain href and from a page by using php dom and that href - www.imdb.com/title/tt-some-id contains the word imdb so in the example below i try to get the href by using php function strpos to look for the word imdb but it don't seen to work. 我正在尝试使用php dom来获取某个href,并从页面获取该www.imdb.com/title/tt-some-id包含单词imdb因此在下面的示例中,我尝试通过使用php函数strpos来查找单词imdb但是它没有起作用。

$page = 'www.someurl.com';
$data = array();
$dom = new DOMDocument();
@$dom->loadHTML($page);

$data['imdb_link'];

$links = $dom->getElementsByTagName('a');
foreach ($links as $link) {
    $href = $link->getAttribute('href');
    if (false !== strpos($href,'imdb')) {
        $data['imdb_link'] = $href;
    } else {
        $data['imdb_link'] = '';
    }
}

And the links from the page 以及页面中的链接

<a href="some-url.com"></a>
<a href="www.imdb.com/title/some-id"></a>
<a href="another-url.com"></a>
<a href="another-url.com"></a>

Could someone please tell me why it ain't working thanks 有人可以告诉我为什么它不起作用谢谢

You could move the logic to Xpath, too. 您也可以将逻辑移至Xpath。 The result will be an empty string of no matching element is found: 结果将是找不到匹配元素的空字符串:

$page='<a href="some-url.com"></a>
<a href="www.imdb.com/title/some-id"></a>
<a href="another-url.com"></a>
<a href="another-url.com"></a>';
$dom = new DOMDocument();
@$dom->loadHTML($page);
$xpath = new DOMXpath($dom);

$data['imdb_link'] = $xpath->evaluate(
  'string(//a[contains(@href, "imdb")]/@href)'
);
var_dump($data);

Output: https://eval.in/149602 输出: https : //eval.in/149602

array(1) {
  ["imdb_link"]=>
  string(26) "www.imdb.com/title/some-id"
}

That is actually working , but you are overwriting it.. 那实际上是有效的,但是您正在覆盖它。

As you can see your final <a> href does not contain the text imdb , so that will be overwritten by your previously found result by your else statement. 如您所见,最终的<a> href不包含文本imdb ,因此您的else语句将先前发现的结果覆盖。

Well how to fix it ? 那么如何解决呢?

Just remove the else part from your code. 只需从代码中删除else部分。

Working Demo 工作演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM