我有一个简单的 PHP 一维数组。
当我执行 var dump (echo var_dump($a)) 时,我将其作为输出:
array(3) { [0]=> string(3) "尽" [1]=> string(21) "exhausted||to exhaust" [2]=> string(4) "jin3" }
但是,当我对它进行 json_encode (echo json_encode($a)) 时,我得到了这个:
["\u5c3d","exhausted||to exhaust","jin3"]
它返回的十六进制值是正确的,但我不知道如何阻止它给我十六进制值。我只是想让它显示角色。
如果我 echo mb_internal_encoding() 它返回 UTF-8,这是我设置的。我在所有字符串操作中都非常小心地使用 mb_ 函数,因此没有数据被弄乱。
我知道我可以编写一个修改后的 json_encode 函数来解决这个问题。但我想知道这里发生了什么。
最佳答案
我知道这个问题比较老,但我想我会借用我在中国工作的 to_json 和 to_utf8 函数——其中包括一些很好的格式 (JSON_PRETTY_PRINT)开发与缩小生产。 (适应自己的环境/系统)
// Produces JSON with Chinese Characters fully un-encoded.
// NOT RFC4627 compliant
json_encode($data, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
function to_json($data, $pretty=null, $inculde_security=false, $try_to_recover=true) {
// @Note: json_encode() *REQUIRES* data to be in valid UTF8 format BEFORE
// trying to json_encode and since we are working with Chinese
// characters, we need to make sure that we explicitly allow:
// JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES
// *Unless a mode is explicitly passed into the function
$json_encoded = '{}';
if ($pretty === null && is_env_prod()) { // @NOTE: Substitute with your own Production env check
$json_encoded = json_encode( $data, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES );
} else if ($pretty === null && is_env_dev()){ // @NOTE: Substitute with your own Development env check
$json_encoded = json_encode( $data, JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES );
} else {
// PRODUCTION
$json_encoded = json_encode( $data, $pretty );
}
// (1) Do not return an error if the inital data was empty
// (2) Return an error if json_encode() failed
if (json_last_error() > 0) {
if (!!$data || !empty($data)) {
if (!$json_encoded == false || empty($json_encoded) || $json_encoded == '{}') {
$json_encoded = json_encode([
'status' => false,
'error' => [
'json_last_error' => json_last_error(),
'json_last_error_msg' => json_last_error_msg()
]
]);
} else if (!!$try_to_recover) {
// there was data in $data so lets try to forensically recover a little? by removing $k => $v pairs that fail to be JSON encoded
foreach (((array) $data) as $k => $v) {
if (!json_encode([$k => $v])) {
if (is_array($data)) {
unset($data[$k]);
} else if (is_object($data)) {
unset($data->{$k});
}
}
}
// if the data still is not empty, and there is a status set in the data
// then set it to false and add a error message/data
// ONLY for Array & Objects
if (!empty($json_encoded) && count($json_encoded) < 1) {
if (!json_encode($data)) {
if (is_array($json_encoded)) {
$json_encoded['status'] = false;
$json_encoded['message'] = "json_encoding_error";
$json_encoded['error'] = [
'json_last_error' => json_last_error(),
'json_last_error_msg' => json_last_error_msg()
];
} else if (is_object($json_encoded)) {
$json_encoded->status = false;
$json_encoded->message = "json_encoding_error";
$json_encoded->error = [
'json_last_error' => json_last_error(),
'json_last_error_msg' => json_last_error_msg()
];
}
} else {
// We have removed the offending data
return to_json($data, $pretty, $include_security, $try_to_recover);
}
}
// we've cleaned out any data that was causing the problem, and included
// false to indicate this is a one-time recursion recovery.
return $this->to_json($pretty, $include_security, false);
}
} else { } // don't do anything as the value is already false
}
return ( ($inculde_security) ? ")]}',\n" : '' ) . $json_encoded;
}
另一个可能有用的函数是我的递归 to_utf8() 功能:
// @NOTE: Common Chinese GBK encoding: to_utf8($data, 'GB2312')
function to_utf8($in, $source_encoding='HTML-ENTITIES') {
if (is_string($in)) {
return mb_convert_encoding(
$in,
$source_encoding,
'UTF-8'
);
} else if (is_array($in) || is_object($in)) {
array_walk_recursive($in, function(&$item, &$key) {
$key = to_utf8($key);
if (is_object($item) || is_array($item)) {
$item = to_utf8($item);
} else {
if (!mb_detect_encoding($item, 'UTF-8', true)){
$item = utf8_encode($item);
}
}
});
$ret_object = is_object($in);
return ($ret_object) ? (object) $in : (array) $in;
}
return $in;
}
$pcre_regex = '
/
(?(DEFINE)
(?<number> -? (?= [1-9]|0(?!\d) ) \d+ (\.\d+)? ([eE] [+-]? \d+)? )
(?<boolean> true | false | null )
(?<string> " ([^"\\\\]* | \\\\ ["\\\\bfnrt\/] | \\\\ u [0-9a-f]{4} )* " )
(?<array> \[ (?: (?&json) (?: , (?&json) )* )? \s* \] )
(?<pair> \s* (?&string) \s* : (?&json) )
(?<object> \{ (?: (?&pair) (?: , (?&pair) )* )? \s* \} )
(?<json> \s* (?: (?&number) | (?&boolean) | (?&string) | (?&array) | (?&object) ) \s* )
)
\A (?&json) \Z
/six
';
$matches = false;
preg_match($pcre_regex, trim($body), $matches);
var_dump('RFC4627 Verification (Regex) ', [
'has_passed' => (count($matches) == 1) ? 'YES' : 'NO',
'matches' => $matches
]);
// One Liner
is_string($json_string) && !preg_match('/[^,:{}\\[\\]0-9.\\-+Eaeflnr-u \\n\\r\\t]/', preg_replace('/"(\\.|[^"\\\\])*"/', '', $json_string));
// Alt Function — more consistant
function is_json($json_string) {
if (!is_string($json_string) || is_numeric($json_string)) {
return false;
}
$val = @json_decode($json_string);
return ($val != null) && (json_last_error() === JSON_ERROR_NONE);
// Inconsistant results, reverted to json_decode() + JSON_ERROR_NONE check
// return is_string($json_string) && !preg_match('/[^,:{}\\[\\]0-9.\\-+Eaeflnr-u \\n\\r\\t]/', preg_replace('/"(\\.|[^"\\\\])*"/', '', $json_string));
}
function is_utf8($str) {
if (is_array($str)) {
foreach ($str as $k=>$v) {
if (is_string($v) && !is_utf8($v)) {
return false;
}
}
}
return (is_string($str) && preg_match('//u', $str));
}
关于php - PHP 中的 json_encode() 返回转义 Unicode 中的汉字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1814585/
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时
作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代
在我的Rails(2.3,Ruby1.8.7)应用程序中,我需要将字符串截断到一定长度。该字符串是unicode,在控制台中运行测试时,例如'א'.length,我意识到返回了双倍长度。我想要一个与编码无关的长度,以便对unicode字符串或latin1编码字符串进行相同的截断。我已经了解了Ruby的大部分unicode资料,但仍然有些一头雾水。应该如何解决这个问题? 最佳答案 Rails有一个返回多字节字符的mb_chars方法。试试unicode_string.mb_chars.slice(0,50)
Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题
我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何
为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返
我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer
刚入门rails,开始慢慢理解。有人可以解释或给我一些关于在application_controller中编码的好处或时间和原因的想法吗?有哪些用例。您如何为Rails应用程序使用应用程序Controller?我不想在那里放太多代码,因为据我了解,每个请求都会调用此Controller。这是真的? 最佳答案 ApplicationController实际上是您应用程序中的每个其他Controller都将从中继承的类(尽管这不是强制性的)。我同意不要用太多代码弄乱它并保持干净整洁的态度,尽管在某些情况下ApplicationContr
如何匹配未被反斜杠转义的平衡定界符对(其本身未被反斜杠转义)(无需考虑嵌套)?例如对于反引号,我试过了,但是转义的反引号没有像转义那样工作。regex=/(?!$1:"how\\"#expected"how\\`are"上面的正则表达式不考虑由反斜杠转义并位于反引号前面的反斜杠,但我愿意考虑。StackOverflow如何做到这一点?这样做的目的并不复杂。我有文档文本,其中包括内联代码的反引号,就像StackOverflow一样,我想在HTML文件中显示它,内联代码用一些spanMaterial装饰。不会有嵌套,但转义反引号或转义反斜杠可能出现在任何地方。