无法分析PHP字符串中的符号和

无法分析PHP字符串中的符号和,php,ampersand,Php,Ampersand,我试图解析PHP字符串中的符号和值。在我运行代码后,它一直返回空值,我确信这是因为变量($area)中的“与”值。我试过htmlspecialchars,html_实体_解码,但没用。请参阅下面的代码: <?php /** Create HTTP POST */ $accomm = 'ACCOMM'; $state = ''; $city = 'Ballan'; $area = 'Daylesford & Macedon Ranges'; $page = '10'; $seek

我试图解析PHP字符串中的符号和值。在我运行代码后,它一直返回空值,我确信这是因为变量($area)中的“与”值。我试过htmlspecialchars,html_实体_解码,但没用。请参阅下面的代码:

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

?>

请问我该如何解决这个问题
谢谢,XML不是HTML,反之亦然。XML文档中不能有裸
&
,因为它是XML文档中的特殊字符。如果您只是像这样定义一个静态字符串,您可以用
&;替换它并继续你的一天

如果需要对可能包含或不包含
&
或其他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;.");
函数xmlentity\u encode($input){
$match=array(“/&/”、“//”、“/\”/”、“/”);
$replace=数组(“&;”、“、”、“&apos;”、“”);
返回preg_replace($match,$replace,$input);
}
函数xmlentity_decode($input){
$match=array('/&;/'、'/'、'/'、'/&apos;/'、'/“/”);
$replace=数组('&',''''''''''''''''''''');
返回preg_replace($match,$replace,$input);
}
echo xmlentity_encode(“这是测试&东西\”n.)。“\n”;
echo xmlentity_decode(“这是测试&apos;东西“n垃圾”);
输出:

This is testing &amp; &apos;stuff&quot; n &gt;junk&lt;.
This is testing & 'stuff" n <junk>.
这是测试&&载脂蛋白;垃圾。
这是测试&“东西”n。

我相当肯定PHP的XML库可以透明地为您实现这一点,[并尊重字符集],但如果您手动构建自己的XML文档,则必须确保您知道类似的情况。

什么会返回空白值?为什么您确定问题是由于
$area
中的值而发生的?为什么在将实体放入
$seek
变量之前不对其进行编码(因为非编码的
&
在XML中通常无效,除非在CDATA块内)?@andreimarinescu:这不起作用@Mike Brant:我在发布之前就这样做了,并且没有返回任何值;我的信心是基于我以前使用相同代码进行的测试;例如,如果我为$area提供了另一个不需要编码的值,代码将从API网站返回结果;因为它是一个静态值,但令人惊讶的是它没有返回任何值。这才是真正让我困惑的。。根据你的密码,我不明白。。