php domxpath不使用concat函数

时间:2015-04-08 09:57:40

标签: php xpath

我从http://www.bodybuilding.com/store/accelerative/accelerative.htm

解析网址

使用xpath:

concat( 'http://www.bodybuilding.com', //div[@class='product-details']/h3/a/@href)

但它不起作用

我尝试过其他查询

//`div[@class='product-details']/h3/a[concat('abc',@href)]` 

然后它工作

这个代码出了什么问题?

我正在使用

Apache/2.4.4 (Win32) OpenSSL/0.9.8y PHP/5.4.19
DOM/XML enabled
DOM/XML API Version 20031129
libxml Version  2.7.8
HTML Support    enabled
XPath Support   enabled
XPointer Support    enabled
Schema Support  enabled
RelaxNG Support enabled

1 个答案:

答案 0 :(得分:1)

将节点集传递给concat()不能按预期工作。 concat()期望它的参数是字符串。

以下代码怎么样?

$url = 'http://www.bodybuilding.com/store/accelerative/accelerative.htm';
$baseUrl = 'http://www.bodybuilding.com';

$doc = new DOMDocument();
@$doc->loadHTMLFile($url);
$selector = new DOMXPath($doc);

$xpath = '//div[@class="product-details"]/h3/a/@href';

foreach($selector->query($xpath) as $node) {
    var_dump($baseUrl . $node->nodeValue);
}

输出:

string(47) "http://www.bodybuilding.com/store/opt/whey.html"
string(47) "http://www.bodybuilding.com/store/opt/whey.html"
string(47) "http://www.bodybuilding.com/store/opt/whey.html"
string(47) "http://www.bodybuilding.com/store/opt/whey.html"
string(47) "http://www.bodybuilding.com/store/opt/whey.html"
string(47) "http://www.bodybuilding.com/store/opt/whey.html"
string(47) "http://www.bodybuilding.com/store/opt/whey.html"
string(47) "http://www.bodybuilding.com/store/opt/whey.html"
string(50) "http://www.bodybuilding.com/store/jym/pre-jym.html"
string(65) "http://www.bodybuilding.com/store/opt/essential-amino-energy.html"
string(65) "http://www.bodybuilding.com/store/opt/essential-amino-energy.html"
string(65) "http://www.bodybuilding.com/store/opt/essential-amino-energy.html"
string(65) "http://www.bodybuilding.com/store/opt/essential-amino-energy.html"
string(63) "http://www.bodybuilding.com/store/rsp-nutrition/quadralean.html"
string(63) "http://www.bodybuilding.com/store/rsp-nutrition/quadralean.html"
string(48) "http://www.bodybuilding.com/store/bsn/synth.html"
string(48) "http://www.bodybuilding.com/store/bsn/synth.html"
string(48) "http://www.bodybuilding.com/store/bsn/synth.html"
string(48) "http://www.bodybuilding.com/store/bsn/synth.html"
string(50) "http://www.bodybuilding.com/store/cellucor/c4.html"
相关问题