问题
I am trying to parse the ampersand value in a PHP string. It keeps returning blank values after I run my code and I am sure it is because of the 'ampersand' value in my variable ($area). I tried htmlspecialchars, html_entity_decode but to no avail. Please see code below:
<?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);
?>
Pls how do I fix this Thanks
回答1:
XML is not HTML, and vice-versa. You cannot have a bare &
in an XML document since it is a special character in XML documents. If you're just defining a static string like this your can replace it with &
and move on with your day.
If you need to encode arbitrary strings that may or may not contain &
or another XML special char, then you'll need functions like:
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<.");
Output:
This is testing & 'stuff" n >junk<.
This is testing & 'stuff" n <junk>.
I'm fairly sure that PHP's XML libs do this for you transparently, [and also respecting the character set] but if you're manually constructing your own XML document then you have to ensure that you're aware of things like this.
来源:https://stackoverflow.com/questions/20153892/unable-to-parse-ampersand-in-php-string