将php变量转换为XML请求字符串 [英] Php variable into a XML request string

查看:160
本文介绍了将php变量转换为XML请求字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,这是使用ref asrist代码从XML文件中提取演出者名称的.

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 ?>

我的问题: 我可以将php代码生成的变量插入xml请求字符串吗? 如果可以的话,请您告知我从哪里开始阅读...

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 ...

谢谢

推荐答案

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

这篇关于将php变量转换为XML请求字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆