【发布时间】:2011-08-11 13:52:29
【问题描述】:
我正在使用 curl 获取一个可以位于此处的 json 文件:(复制粘贴太长了):http://www.opap.gr/web/services/rs/betting/availableBetGames/sport/program/4100/0/sport-1.json?localeId=el_GR
之后我使用 json_decode 来获取关联数组。直到这里一切正常。当我使用 var_dump 时,数组中的字符是希腊语。之后我使用以下代码:
$JsonClass = new ArrayToXML();
$mydata=$JsonClass->toXml($json);
类 ArrayToXML {
public static function toXML( $data, $rootNodeName = 'ResultSet', &$xml=null ) {
// turn off compatibility mode as simple xml throws a wobbly if you don't.
// if ( ini_get('zend.ze1_compatibility_mode') == 1 ) ini_set ( 'zend.ze1_compatibility_mode', 0 );
if ( is_null( $xml ) ) //$xml = simplexml_load_string( "" );
$xml = simplexml_load_string("<?xml version='1.0' encoding='UTF-8'?><$rootNodeName />");
// loop through the data passed in.
foreach( $data as $key => $value ) {
$numeric = false;
// no numeric keys in our xml please!
if ( is_numeric( $key ) ) {
$numeric = 1;
$key = $rootNodeName;
}
// delete any char not allowed in XML element names
`enter code here`$key = preg_replace('/[^a-z0-9\-\_\.\:]/i', '', $key);
// if there is another array found recrusively call this function
if ( is_array( $value ) ) {
$node = ArrayToXML::isAssoc( $value ) || $numeric ? $xml->addChild( $key ) : $xml;
// recrusive call.
if ( $numeric ) $key = 'anon';
ArrayToXML::toXml( $value, $key, $node );
} else {
// add single node.
$value = htmlentities( $value );
$xml->addChild( $key, $value );
}
}
// pass back as XML
return $xml->asXML();
}
public static function isAssoc( $array ) {
return (is_array($array) && 0 !== count(array_diff_key($array, array_keys(array_keys($array)))));
}
}
问题来了。结果中的所有希腊字符都是一些奇怪的字符&Icirc;?&Icirc;?&Icirc;&yen;&Icirc;?&Icirc;?&Icirc;&iexcl;&Icirc;&copy;&Icirc;&pound;&Icirc;?&Icirc;? 例如。我真的不知道我做错了什么。我对编码/解码的东西真的很不好:( .
为了更清楚一点:
下面是关联数组(在我遇到问题的部分)的样子:
{ ["resources"]=> array(4) { ["team-4833"]=> string(24) "ΛΕΥΚΟΡΩΣΙΑ U21" ["t-429"]=> string(72) "ΠΡΟΚΡΙΜΑΤΙΚΑ ΕΥΡΩΠΑΪΚΟΥ ΠΡΩΤΑΘΛΗΜΑΤΟΣ" ["t-429-short"]=> string(6) "ΠΕΠ" ["team-15387"]=> string(16) "ΕΛΛΑΔΑ U21" } ["locale"]=> string(5) "el_GR" } ["relatedNum"]=> NULL }
这是我使用 simplexml 后得到的结果
<resources><team-4833>Î?Î?Î¥Î?Î?ΡΩΣÎ?Î? U21</team-4833><t-429>ΠΡÎ?Î?ΡÎ?Î?Î?ΤÎ?Î?Î? Î?ΥΡΩΠÎ?ΪÎ?Î?Î¥ ΠΡΩΤÎ?Î?Î?Î?Î?Î?ΤÎ?Σ</t-429><t-429-short>Î Î?Î </t-429-short><team-15387>Î?Î?Î?Î?Î?Î? U21</team-15387></resources><locale>el_GR</locale></lexicon><relatedNum></relatedNum></betGames>
提前感谢您的回复。
PS:我也有<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />在我显示结果的页面中,但它没有帮助。
我仍然没有找到解决方案,所以我使用了 Yannis 建议的不同方法。我使用我在此处找到的类 http://www.phpclasses.org/package/1826-PHP-Store-associative-array-data-on-file-in-XML.html 将 XML 保存在一个文件中。
之后,我使用 simplexml_load_file 加载 xml,并使用 xslt 访问所有节点中的数据并将其存储在我的数据库中。那样工作得很好。如果有人仍然想尝试解释为什么它不起作用以我一开始尝试的方式,请随意(仅出于学习目的:p)感谢您的回复:)。
【问题讨论】:
标签: php json unicode utf-8 simplexml