xpath 通过 div id 获取无效
xpath get by div id not working
我的脚本没有得到任何结果(空白页),我不明白为什么
我在其他网站和工作中使用过此脚本
$url = 'http://ip-score.com/checkip/207.224.78.193';
libxml_use_internal_errors(true);
$html = file_get_contents($url);
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$my_xpath_query = "//div[@id='MaxMind']";
$result_rows = $xpath->query($my_xpath_query);
foreach ($result_rows as $result_object){
echo $result_object->childNodes->item(0)->nodeValue;
}
我得到这个结果的方面:
207.224.78.193 United States
State: Minnesota
City: Minneapolis
ZIP: 55407
Hostname: 207-224-78-193.mpls.qwest.net, Whois
Organization: CenturyLink, History
ISP: CenturyLink
Mail Server: N\A
IP range: 207.224.71.0 - 207.224.97.191
Current region time: Thu 12th Mar 2015 - 02:52:15 GMT: -05:00
Region timezone: America/Chicago
我想从 url(state,city,zip...) 获取所有信息,但我无法一一获取,所以我决定获取所有信息,然后将其拆分为 var
您的 xpath 表达式当前正在寻找 div 作为文档的根元素。您可能想使用 //div[@id='MaxMind']
来搜索整个文档,或者只使用 $dom->getElementById("MaxMind")
因为 xpath 对于这个查询来说并不是真正需要的。
同样值得注意的是:该元素的第一个子元素只是一个全白的文本节点 space。要转储 div 中的所有内容,请替换
echo $result_object->childNodes->item(0)->nodeValue;
和
echo $result_object->nodeValue;
不过,如果您想以更合理的方式处理这些内容,而不只是一团文本,像 //div[@id='MaxMind']/p
这样的 xpath 表达式将为您提供每个 "line"。
我的脚本没有得到任何结果(空白页),我不明白为什么 我在其他网站和工作中使用过此脚本
$url = 'http://ip-score.com/checkip/207.224.78.193';
libxml_use_internal_errors(true);
$html = file_get_contents($url);
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$my_xpath_query = "//div[@id='MaxMind']";
$result_rows = $xpath->query($my_xpath_query);
foreach ($result_rows as $result_object){
echo $result_object->childNodes->item(0)->nodeValue;
}
我得到这个结果的方面:
207.224.78.193 United States
State: Minnesota
City: Minneapolis
ZIP: 55407
Hostname: 207-224-78-193.mpls.qwest.net, Whois
Organization: CenturyLink, History
ISP: CenturyLink
Mail Server: N\A
IP range: 207.224.71.0 - 207.224.97.191
Current region time: Thu 12th Mar 2015 - 02:52:15 GMT: -05:00
Region timezone: America/Chicago
我想从 url(state,city,zip...) 获取所有信息,但我无法一一获取,所以我决定获取所有信息,然后将其拆分为 var
您的 xpath 表达式当前正在寻找 div 作为文档的根元素。您可能想使用 //div[@id='MaxMind']
来搜索整个文档,或者只使用 $dom->getElementById("MaxMind")
因为 xpath 对于这个查询来说并不是真正需要的。
同样值得注意的是:该元素的第一个子元素只是一个全白的文本节点 space。要转储 div 中的所有内容,请替换
echo $result_object->childNodes->item(0)->nodeValue;
和
echo $result_object->nodeValue;
不过,如果您想以更合理的方式处理这些内容,而不只是一团文本,像 //div[@id='MaxMind']/p
这样的 xpath 表达式将为您提供每个 "line"。