Php 变量转换为 XML 请求字符串


Php variable into a XML request string

我有以下代码,它正在使用 ref asrist 代码从 XML 文件中提取艺术家姓名。

<?php
    $dom = new DOMDocument();
    $dom->load('http://www.bookingassist.ro/test.xml');
    $xpath = new DOMXPath($dom);
    echo $xpath->evaluate('string(//Artist[ArtistCode = "COD Artist"] /ArtistName)');
    ?>

基于搜索提取艺术家代码的代码

<?php echo $Artist->artistCode ?>

我的问题 :我可以将 php 代码生成的变量插入到 xml 请求字符串中吗?如果是这样,你能告诉我我从哪里开始阅读......

谢谢

你的意思是 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);