且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将php变量转换为XML请求字符串

更新时间:2023-09-06 12:55:04

您的意思是XPath表达式.是的,您可以-它只是一个字符串".

You mean the XPath expression. Yes you can - it is "just a string".

$expression = 'string(//Artist[ArtistCode = "'.$Artist->artistCode.'"]/ArtistName)'
echo $xpath->evaluate($expression);

但是您必须确保结果是有效的XPath,并且您的值不会破坏字符串文字.不久前,我为一个库编写了一个函数,该函数以这种方式准备了一个字符串.

But you have to make sure that the result is valid XPath and your value does not break the string literal. I wrote a function for a library some time ago that prepares a string this way.

XPath 1.0中的问题在于,这里无法转义任何特殊字符.如果字符串包含要在XPath中使用的引号,则它将破坏表达式.该函数使用字符串中未使用的引号,或者如果使用了引号,则将字符串拆分并将部分放入concat()调用中.

The problem in XPath 1.0 is that here is no way to escape any special character. If you string contains the quotes you're using in XPath it breaks the expression. The function uses the quotes not used in the string or, if both are used, splits the string and puts the parts into a concat() call.

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.

The function generates the needed XPath.

$expression = 'string(//Artist[ArtistCode = '.quoteXPathLiteral($Artist->artistCode).']/ArtistName)'
echo $xpath->evaluate($expression);