我正在尝试将一长串xpath查询测试列入一个更加简洁的函数,并且在从mysql中提取xpath查询后会出现问题。
这让我感到沮丧,有人可以解释我哪里出错吗?
示例MySQL表:
CREATE TABLE `spidey_regex` (
`id` int(12) NOT NULL auto_increment,
`regexp` varchar(255) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM;
INSERT INTO `spidey_regex` (`id`, `regexp`) VALUES (1, '''//div[starts-with(@id, "stuff")]''');
使用xpath的示例PHP代码:
<?php
$html = '<div id="stuff123"><a href="link1.html">Link 1</a><a href="#link">Link 2</a><a href="link2.html">Link 3</a></div>';
$cnt=0;
$dom = new DOMDocument();
@$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;
$xpath = new DOMXPath($dom);
$myresult = mysql_query("select * from spidey_regex",$db);
while($myrow = mysql_fetch_array($myresult)){
$regexp = stripslashes(trim($myrow[regexp]));
$result = $xpath->query($regexp); // use xpath with query from MySQL
foreach($result as $e){ $cnt++; }
if($cnt == '0'){
continue;
}
else {
echo "1. Got here!!";
}
}
?>
答案 0 :(得分:0)
INSERT INTO `spidey_regex` (`id`, `regexp`) VALUES (1, '''//div[starts-with(@id, "stuff")]''');
双引号逃避的事情有点奇怪。如果我们使用正常的反斜杠,我们会看到:
'\'//div[starts-with(@id, "stuff")]\''
换句话说,您的XPath查询有太多引号层,并且被XPath解析器拒绝。从数据库中的值中删除引号后,您的查询应该可以正常工作。
PHP Interactive提示证明:
php > $html = '<div id="stuff123"><a href="link1.html">Link 1</a><a href="#link">Link 2</a><a href="link2.html">Link 3</a></div>';
php > $dom = new DOMDocument();
php > $dom->loadHTML($html);
php > $xpath = new DOMXPath($dom);
php > $regexp = '//div[starts-with(@id, "stuff")]';
php > $result = $xpath->query($regexp);
php > echo $result->length;
1
php > $regexp = "'{$regexp}'";
php > $result = $xpath->query($regexp);
php > echo $result->length;
0