php 如何从 <div>value</div> 中获取价值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8383396/
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-26 04:35:05  来源:igfitidea点击:

How to get value from <div>value</div>?

phpdomdocument

提问by Aryan G

I need to get value from

我需要从中获取价值

<div id = "result">Roll No 103 Pass</div> 

and out put should be : Roll No 103 Pass

并且输出应该是:Roll No 103 Pass

I used this code :

我使用了这个代码:

$markup = file_get_contents('www.results.com');
$doc = new DomDocument();
@$file = $doc->loadHTML($markup);
$spans = $doc->getElementsByTagName('div');
foreach($spans AS $span)
    {
    $class = $span -> getElementsById('id');
    if($class=="result") { 
        echo $span -> nodeValue;


    }


}

but it just return blank screen

但它只是返回空白屏幕

回答by Francis Avila

$doc = new DomDocument();
$doc->loadHTMLFile('http://www.results.com');
$thediv = $doc->getElementById('result');
echo $thediv->textContent;

回答by Felix Kling

Two remarks:

两点说明:

  1. IDs have to be unique, so there is little sense in looping over elements and search for an element with a specific ID in them. Just get the element directly.
  2. You can get the inner text with the textContent[docs]property.
  1. ID 必须是唯一的,因此循环遍历元素并搜索其中具有特定 ID 的元素是没有意义的。直接获取元素即可。
  2. 您可以使用textContent[docs]属性获取内部文本。

Example:

例子:

$div = $doc->getElementById('result');
if($div) {
    echo $div->textContent;
}