Php variable into a XML request string

前端 未结 1 1291
北海茫月
北海茫月 2020-12-04 04:15

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

loa         


        
相关标签:
1条回答
  • 2020-12-04 04:46

    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);
    
    0 讨论(0)
提交回复
热议问题