【问题标题】:Getting elements of a div from another page (PHP)从另一个页面获取 div 的元素 (PHP)
【发布时间】:2011-06-30 01:22:38
【问题描述】:

所以我有第一页:

<div id="div1">This is text one</div>

<div id="div2">This is text two</div>

<div id="div3">This is text three</div>

现在我想获取 div 1 的元素,它会返回 This is text one,我该怎么做?

【问题讨论】:

  • 那么,您只想使用 php 从另一个页面抓取 div1 内的文本?

标签: php string html file-get-contents


【解决方案1】:

您可以在 PHP 中使用 DOMDocument:

<?php

$doc = new DomDocument;

// We need to validate our document before refering to the id
$doc->validateOnParse = true;
$doc->loadHtml(file_get_contents('http://google.com/bla.php'));

var_dump($doc->getElementById('div1'));

?>

【讨论】:

  • 如果'div1'的内容本来是空的,被javascript加载了怎么办?
  • @teuneboon 如果网页是由 javascript 动态生成的怎么办?这种情况下怎么办?
【解决方案2】:
$string = file_get_contents($url);
if (preg_match('/<div id="div1">([^<]*)<\/div>/', $string, $matches) > 0) {
    echo $matches[1]; //This is text one
}

【讨论】:

  • 强烈建议不要使用正则表达式来解析 html。您可以为此使用 DomDocument
  • DomDocument 不适合我,这个脚本节省了我的时间!我投票给了这位用户,因为他与我们分享了一个非常有用的 sn-p,谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-09-04
  • 2020-12-21
  • 2015-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多