2013-11-22 39 views
0

我想解析PHP字符串中的&符号值。在我运行我的代码后,它保持返回空白值,我确信这是因为我的变量($区域)中的“&”值。我试过htmlspecialchars,html_entity_decode但无济于事。请看下面的代码:无法解析PHP字符串中的&符号

<?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我怎么解决这个 感谢

+0

尝试urlencode($面积) – andreimarinescu

+0

什么返回空白值?为什么你确定你的问题是因为'$ area'中的值而出现的?为什么在将实体放入'$ seek'变量之前不对它们进行编码(因为非编码的'&'通常在XML中无效,除非在CDATA块中)? –

+0

@andreimarinescu:不起作用 – akinboj

回答

2

XML不是HTML,反之亦然。 XML文档中不能包含&,因为它是XML文档中的特殊字符。如果你只是像这样定义一个静态字符串,你可以用&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>. 

我m相当肯定,PHP的XML库为你做透明地,[并且也尊重字符集],但如果你手动构建自己的XML文档,那么你必须确保你知道像 这个。

+0

是的,我试图用&替换它,因为它是一个静态值,但令人惊讶的是它不返回任何值。这真是让我感到困惑。根据你的代码,我不明白它.. – akinboj