Php variable into a XML request string

喜欢而已 提交于 2019-12-17 14:57:06

问题


I have the below code wich is extracting the Artist name from a XML file with the ref asrist code.

<?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)');
    ?>

The code that is pulling the artistcode based on a search

<?php echo $Artist->artistCode ?>

My question : Can i insert the variable generated by the php code into the xml request string ? If so could you please advise where i start reading ...

Thanks


回答1:


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

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

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.

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."'";
  }
}

The function generates the needed XPath.

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


来源:https://stackoverflow.com/questions/27439368/php-variable-into-a-xml-request-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!