Unable to Parse ampersand in PHP string

一个人想着一个人 提交于 2019-12-13 06:24:58

问题


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 &amp; 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('&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;.");

Output:

This is testing &amp; &apos;stuff&quot; n &gt;junk&lt;.
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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!