【问题标题】:Unable to Parse ampersand in PHP string无法解析 PHP 字符串中的 & 符号
【发布时间】:2013-12-07 20:47:37
【问题描述】:

我正在尝试解析 PHP 字符串中的 & 值。在我运行我的代码后它一直返回空白值,我确信这是因为我的变量($area)中的“&”值。我尝试了 htmlspecialchars、html_entity_decode 但无济于事。请看下面的代码:

<?php

/** Create HTTP POST */
$accomm = 'ACCOMM';
$state = '';
$city = 'Ballan';
$area = 'Daylesford & Macedon Ranges';
$page = '10';

$seek = '<parameters> 

<row><param>SUBURB_OR_CITY</param><value>'. $city .'</value></row>
<row><param>AREA</param><value>'. $area .'</value></row>

</parameters>';

$postdata = http_build_query(
array(
 'DistributorKey' => '******',
 'CommandName' => 'QueryProducts',
 'CommandParameters' => $seek)
);

$opts = array(
'http' => array(
'method'  => 'POST',
'header'  => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata)
);

/** Get string output of XML (In URL instance) */

$context  = stream_context_create($opts);
$result =   file_get_contents('http://national.atdw.com.au/soap/AustralianTourismWebService.asmx/CommandHandler?', false, $context);

?>

请问我该如何解决这个问题 谢谢

【问题讨论】:

  • 什么返回空白值?为什么你确定你的问题是因为$area 中的值而发生的?为什么在将实体放入 $seek 变量之前不对其进行编码(因为未编码的 &amp; 通常在 XML 中无效,除非在 CDATA 块内)?
  • @andreimarinescu:这行不通
  • @Mike Brant:我在发帖之前就这样做了,没有返回任何值;我的信心是基于我之前使用相同代码进行的测试;例如,如果我为 $area 提供了另一个不需要编码的值,则代码会从 API 网站返回结果。

标签: php ampersand


【解决方案1】:

XML 不是 HTML,反之亦然。您不能在 XML 文档中使用纯 &amp;amp;,因为它是 XML 文档中的特殊字符。如果您只是定义这样的静态字符串,您可以将其替换为 &amp;amp; 并继续您的一天。

如果您需要对可能包含或不包含 &amp;amp; 或其他 XML 特殊字符的任意字符串进行编码,那么您将需要以下函数:

function xmlentity_encode($input) {
    $match = array('/&/', '/</', '/>/', '/\'/', '/"/');
    $replace = array('&amp;', '&gt;', '&lt;', '&apos;', '&quot;');
    return preg_replace($match, $replace, $input);
}

function xmlentity_decode($input) {
    $match = array('/&amp;/', '/&gt;/', '/&lt;/', '/&apos;/', '/&quot;/');
    $replace = array('&', '<', '>', '\'', '"');
    return preg_replace($match, $replace, $input);
}

echo xmlentity_encode("This is testing & 'stuff\" n <junk>.") . "\n";
echo xmlentity_decode("This is testing &amp; &apos;stuff&quot; n &gt;junk&lt;.");

输出:

This is testing &amp; &apos;stuff&quot; n &gt;junk&lt;.
This is testing & 'stuff" n <junk>.

我相当确定 PHP 的 XML 库会为您做到这一点透明,[并且还尊重字符集] 但是如果您手动构建自己的 XML 文档,那么您必须确保你知道这样的事情。

【讨论】:

  • 是的,我尝试将其替换为 &因为它是一个静态值,但令人惊讶的是它不返回任何值。这真是让我感到困惑..根据你的代码,我不明白..
猜你喜欢
  • 2020-05-01
  • 1970-01-01
  • 2014-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多