我正在尝试解析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);
?>
请问我该怎么修感谢
XML不是HTML,反之亦然。XML文档中不能有空的&
,因为它是XML文档中的一个特殊字符。如果你只是定义一个像这样的静态字符串,你可以用&
替换它,然后继续你的一天。
如果您需要对可能包含也可能不包含&
或其他XML特殊字符的任意字符串进行编码,那么您需要以下函数:
function xmlentity_encode($input) {
$match = array('/&/', '/</', '/>/', '/'/', '/"/');
$replace = array('&', '>', '<', ''', '"');
return preg_replace($match, $replace, $input);
}
function xmlentity_decode($input) {
$match = array('/&/', '/>/', '/</', '/'/', '/"/');
$replace = array('&', '<', '>', ''', '"');
return preg_replace($match, $replace, $input);
}
echo xmlentity_encode("This is testing & 'stuff" n <junk>.") . "n";
echo xmlentity_decode("This is testing & 'stuff" n >junk<.");
输出:
This is testing & 'stuff" n >junk<.
This is testing & 'stuff" n <junk>.
我确信PHP的XML-Lib可以透明地为您做到这一点,[同时也尊重字符集],但如果您手动构建自己的XML文档,则必须确保您知道这样的事情。