我有一个经典的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>我希望能够获得所有的文字从网页使用php。例如,检查DOMText的nodeType会忘记占位符。
有没有一种简单的方法可以快速获取所有的真实文本(在我的例子中是指所有的英文文本)?
发布于 2015-09-03 18:47:40
假设您只想要body元素的子元素...
示例HTML
<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
var body = document.body;
var textContent = body.textContent || body.innerText;
console.log(textContent); // a bc你需要检查textContent,因为我们的好朋友IE使用的是innerText。
如果你有一个像jQuery这样的库,也就是$('body').text(),那就容易多了。
发布于 2015-09-03 18:49:54
参考:http://www.phpro.org/examples/Get-Text-Between-Tags.html
<?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;
}发布于 2015-09-03 21:31:27
使用DomDocument的textContent属性
<?
error_reporting(-1);
$dom = new DomDocument();
$dom->loadHTML($str);
echo $dom->textContent;结果
Some text
var text = "Hi guys !";
Hello guys
Some text is more important
here is some texthttps://stackoverflow.com/questions/32372980
复制相似问题