php 如何在php中获取div内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6491598/
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
How can I get a div content in php
提问by OHLáLá
I have a div in php(string) and I want to get the content.
我在 php(string) 中有一个 div,我想获取内容。
for example:
例如:
<div id="product_list" style="width:100%; float:none;">
<div>
bla bla bla
</div>
bla bla
</div>
and I want
而且我要
<div>
bla bla bla
</div>
bla bla
The style is changing, I know only the div id.
风格在变,我只知道 div id。
UPDATED
更新
this is my code, same as turbod source and the results are the same too.
这是我的代码,与 turbod 源相同,结果也相同。
so this is the original html
所以这是原来的html
$doc = new DOMDocument();
$doc->loadHTML($buffer);
$id = $doc->getElementById('product_list')
And after this code I get the following: link
在这段代码之后,我得到以下信息:链接
回答by turbod
Use the php DomDocument class. http://www.php.net/manual/en/class.domdocument.php
使用 php DomDocument 类。http://www.php.net/manual/en/class.domdocument.php
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$divContent = $xpath->query('//div[id="product_list"]');
回答by ThW
To save an XML/HTML fragment, you need to save each child node:
要保存 XML/HTML 片段,您需要保存每个子节点:
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$result = '';
foreach($xpath->evaluate('//div[@id="product_list"]/node()') as $childNode) {
$result .= $dom->saveHtml($childNode);
}
var_dump($result);
Output:
输出:
string(74) "
<div>
bla bla bla
</div>
bla bla
"
If you only need the text content, you can fetch it directly:
如果只需要文本内容,可以直接获取:
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
var_dump(
$xpath->evaluate('string(//div[@id="product_list"])')
);
Output:
输出:
string(63) "
bla bla bla
bla bla
"
回答by MastaBaba
Isn't it enough to do...
这样做还不够吗...
$id->nodeValue