【问题标题】:Php variable into a XML request stringphp 变量转换成 XML 请求字符串
【发布时间】:2014-12-12 17:28:44
【问题描述】:

我有以下代码,它使用 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 请求字符串中吗? 如果可以,请您告诉我从哪里开始阅读...

谢谢

【问题讨论】:

标签: php xml string variables


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 2017-01-17
    • 2014-09-05
    • 2018-02-08
    • 2017-12-15
    相关资源
    最近更新 更多