首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >DOM PHP -在网页中查找所有可能的文本(标题,占位符,...)

问DOM PHP -在网页中查找所有可能的文本(标题,占位符,...)
EN

Stack Overflow用户
提问于 2015-09-03 18:20:23
回答 3查看 114关注 0票数 1

我有一个经典的HTML网页

代码语言:javascript
复制
<html>
<head>
  <meta charset="utf-8">
  <title>Some text</title>
  <link rel="stylesheet" href="style.css">
  <script src="script.js"></script>
  <script>
      var text = "Hi guys !";
  </script>
</head>
<body>
    <h1>Hello guys</h1>
    <p>Some text <strong>is more important</strong></p>
    <input value="Here also is some text" placeholder="and here too">
    <a href="not here">here is some text</a>
</body>
</html>

我希望能够获得所有的文字从网页使用php。例如,检查DOMText的nodeType会忘记占位符。

有没有一种简单的方法可以快速获取所有的真实文本(在我的例子中是指所有的英文文本)?

EN

回答 3

Stack Overflow用户

发布于 2015-09-03 18:47:40

假设您只想要body元素的子元素...

示例HTML

代码语言:javascript
复制
<html><head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title> Example</title>
</head>
<body>
  a <div>b<span>c</span></div>
</body></html>

JavaScript

代码语言:javascript
复制
var body = document.body;
var textContent = body.textContent || body.innerText;

console.log(textContent);  //   a bc

你需要检查textContent,因为我们的好朋友IE使用的是innerText。

如果你有一个像jQuery这样的库,也就是$('body').text(),那就容易多了。

Refre This Also

票数 0
EN

Stack Overflow用户

发布于 2015-09-03 18:49:54

参考:http://www.phpro.org/examples/Get-Text-Between-Tags.html

代码语言:javascript
复制
<?php
$html='<html>
<head>
<meta charset="utf-8">
<title>Some text</title>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<script>
  var text = "Hi guys !";
</script>
</head>
<body>
<h1>Hello guys</h1>
<p>Some text <strong>is more important</strong></p>
<input value="Here also is some text" placeholder="and here too">
<a href="not here">here is some text</a>
</body>
</html>';

$content = getTextBetweenTags('body', $html);

foreach( $content as $item )
{
echo $item.'<br />';
}
function getTextBetweenTags($tag, $html, $strict=0)
{
/*** a new dom object ***/
$dom = new domDocument;

/*** load the html into the object ***/
if($strict==1)
{
    $dom->loadXML($html);
}
else
{
    $dom->loadHTML($html);
}

/*** discard white space ***/
$dom->preserveWhiteSpace = false;

/*** the tag by its tag name ***/
$content = $dom->getElementsByTagname($tag);

/*** the array to return ***/
$out = array();
foreach ($content as $item)
{
    /*** add node value to the out array ***/
    $out[] = $item->nodeValue;
}
/*** return the results ***/
return $out;
}
票数 0
EN

Stack Overflow用户

发布于 2015-09-03 21:31:27

使用DomDocument的textContent属性

代码语言:javascript
复制
<?
error_reporting(-1); 

$dom = new DomDocument();
$dom->loadHTML($str);
echo $dom->textContent;

结果

代码语言:javascript
复制
Some text
      var text = "Hi guys !";

    Hello guys
    Some text is more important
    here is some text
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32372980

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档