初学者 PHP XPath 文本显示 [英] Beginner PHP XPath Text Display
问题描述
目标:使用 xpath checker/Firefox 和 PHP 在网页上显示选择性文本.
Goal: Use xpath checker/Firefox and PHP to display selective text on a webpage.
为了在此页面上仅显示名称(文本),需要什么 PHP XPATH 代码?http://steamcommunity.com/profiles/76561197967713768
What would be the PHP XPATH code required in order to display just the name (text) on this page? http://steamcommunity.com/profiles/76561197967713768
使用此代码:
<?php
$html = new DOMDocument();
@$html->loadHtmlFile('http://steamcommunity.com/profiles/76561197967713768');
$xpath = new DOMXPath( $html );
$nodelist = $xpath->query( "//div[@class='persona_name']" );
foreach ($nodelist as $n){
echo $n->nodeValue."\n";
}
?>
我得到mopar410 这个用户也玩过:"的输出我只想让它显示mopar410".我想删除此用户还扮演过:" 部分.
I get the output of "mopar410 This user has also played as:" I would like to only have it display "mopar410". I would like to remove the "This user has also played as:" portion.
虽然有些信息无法通过 xml 访问,当我用 Firefox 中的 xpath 检查器替换上述内容时(示例):
Some information cannot be accessed via xml though, and when I replace the above with this from xpath checker in Firefox (example):
<?php
$html = new DOMDocument();
@$html->loadHtmlFile('http://steamcommunity.com/profiles/76561197967713768');
$xpath = new DOMXPath( $html );
$nodelist = $xpath->query( "/x:html/x:body/x:div[3]/x:div[1]/x:div/x:div/x:div/x:div[3]/x:div[1]']" );
foreach ($nodelist as $n){
echo $n->nodeValue."\n";
}
?>
它不起作用,我收到错误消息.右键单击并查看 XPATH,然后将该 xpath 传输到 PHP 代码的正确方法是什么?
It doesn't work and I get an error. What is the proper method of right-clicking and viewing the XPATH, then transferring that xpath to the PHP code?
Warning: DOMXPath::query(): Undefined namespace prefix in blahblahblah on line 85
Warning: DOMXPath::query(): Invalid expression in blahblahblah on line 85
Warning: Invalid argument supplied for foreach() in blahblahblah on line 86
我是新手.请帮忙.
推荐答案
那是因为 <div class="persona_name">
包含除您想要的文本之外的其他节点和文本.您可以尝试使用 XPath 表达式只获取 <div class="persona_name">
的直接子节点的非空文本节点:
That's because <div class="persona_name">
contains other nodes and texts besides the text you wanted. You can try using XPath expression for getting only non empty text node that is direct child of <div class="persona_name">
:
//div[@class='persona_name']/text()[normalize-space(.)]
这篇关于初学者 PHP XPath 文本显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!