从另一个页面 (PHP) 获取 div 的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5045598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:38:20  来源:igfitidea点击:

Getting elements of a div from another page (PHP)

phpstringhtmlfile-get-contents

提问by Thew

So I have page one:

所以我有第一页:

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

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

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

Now I want to get the elements of div one, that it will return This is text one, how can I do that?

现在我想获得第一个 div 的元素,它会返回This is text one,我该怎么做?

回答by teuneboon

You can use DOMDocument in PHP:

你可以在 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'));

?>

回答by Thew

$string = file_get_contents($url);
if (preg_match('/<div id="div1">([^<]*)<\/div>/', $string, $matches) > 0) {
    echo $matches[1]; //This is text one
}