PHP DOMDocument如何获取这个标签的内容? [英] PHP DOMDocument how to get that content of this tag?
本文介绍了PHP DOMDocument如何获取这个标签的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用domDocument希望解析这个小小的html代码。我正在寻找一个特定的 span
标签,其中特定的 id
。
< span id =CPHCenter_lblOperandName> Hello world< / span>
我的代码:
$ dom = new domDocument;
@ $ dom-> loadHTML($ html); // @将沉默HTML错误和错误配置
$ dom-> preserveWhiteSpace = false;
$ nodes = $ dom-> getElementsByTagName('// span [@ id =CPHCenter_lblOperandName');
foreach($ nodes为$ node){
echo $ node-> nodeValue;
}
但由于某种原因,我认为代码或html有问题(我怎么知道?):
- 当我用
echo count($ nodes) code>结果始终为1
- 节点循环中没有输出任何内容
- 我如何学习这些复杂查询的语法
- 我做错了什么? >您可以使用简单的getElementById:
$ dom-> getElementById('CPHCenter_lblOperandName') - > nodeValue
或以选择方式:
$ selector = new DOMXPath($ dom);
$ list = $ selector-> query('/ html / body // span [@ id =CPHCenter_lblOperandName]');
echo($ list-> item(0) - > nodeValue);
//或
foreach($ list as $ span){
$ text = $ span-> nodeValue;
}
I am using domDocument hoping to parse this little html code. I am looking for a specific span
tag with a specific id
.
<span id="CPHCenter_lblOperandName">Hello world</span>
My code:
$dom = new domDocument;
@$dom->loadHTML($html); // the @ is to silence errors and misconfigures of HTML
$dom->preserveWhiteSpace = false;
$nodes = $dom->getElementsByTagName('//span[@id="CPHCenter_lblOperandName"');
foreach($nodes as $node){
echo $node->nodeValue;
}
But For some reason I think something is wrong with either the code or the html (how can I tell?):
- When I count nodes with
echo count($nodes);
the result is always 1 - I get nothing outputted in the nodes loop
- How can I learn the syntax of these complex queries?
- What did I do wrong?
解决方案
You can use simple getElementById:
$dom->getElementById('CPHCenter_lblOperandName')->nodeValue
or in selector way:
$selector = new DOMXPath($dom);
$list = $selector->query('/html/body//span[@id="CPHCenter_lblOperandName"]');
echo($list->item(0)->nodeValue);
//or
foreach($list as $span) {
$text = $span->nodeValue;
}
这篇关于PHP DOMDocument如何获取这个标签的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文