您的意思是 XPath 表达式。是的,你可以——它“只是一个字符串”。
$expression = 'string(//Artist[ArtistCode = "'.$Artist->artistCode.'"]/ArtistName)'
echo $xpath->evaluate($expression);
但是您必须确保结果是有效的 XPath,并且您的值不会破坏字符串文字。前段时间我为一个库写了一个函数,它以这种方式准备一个字符串。
XPath 1.0 中的问题是这里没有办法转义任何特殊字符。如果您的字符串包含您在 XPath 中使用的引号,它会破坏表达式。该函数使用字符串中未使用的引号,或者,如果两者都使用,则拆分字符串并将部分放入 concat() 调用中。
public function quoteXPathLiteral($string) {
$string = str_replace("\x00", '', $string);
$hasSingleQuote = FALSE !== strpos($string, "'");
if ($hasSingleQuote) {
$hasDoubleQuote = FALSE !== strpos($string, '"');
if ($hasDoubleQuote) {
$result = '';
preg_match_all('("[^\']*|[^"]+)', $string, $matches);
foreach ($matches[0] as $part) {
$quoteChar = (substr($part, 0, 1) == '"') ? "'" : '"';
$result .= ", ".$quoteChar.$part.$quoteChar;
}
return 'concat('.substr($result, 2).')';
} else {
return '"'.$string.'"';
}
} else {
return "'".$string."'";
}
}
该函数生成所需的 XPath。
$expression = 'string(//Artist[ArtistCode = '.quoteXPathLiteral($Artist->artistCode).']/ArtistName)'
echo $xpath->evaluate($expression);