PHPUnit和curl错误的字符集,无法比较相等的字符串

时间:2014-01-20 17:39:24

标签: php curl character-encoding phpunit

我有一个断言的PHPUnit测试: $this->assertEquals(json_encode($expected), json_encode($result));

断言失败,因为字符串的编码不同:(差异实际上是较大的,来自大型json对象)

Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'Wir holen Ihre P\u00e4ckchen im Wunschzeitraum ab.'
+'Wir holen Ihre P\u00c3\u00a4ckchen im Wunschzeitraum ab.'

我从curl请求中获取实际字符串,期望的字符串在php文件中定义为字符串。

我使用以下curl代码从服务器检索JSON:

$headers = array(
"GET /HTTP/1.1",
"User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1",
"Content-type: application/json;charset=\"utf-8\"",
"Accept: application/json",            
"Accept-Language: en-us,en;q=0.5",
"Accept-Encoding: gzip,deflate",
"Accept-Charset: utf-8;q=0.7,*;q=0.7",
"Keep-Alive: 300",      
"Connection: keep-alive");

$ch = curl_init('http://localhost/frontend_test.php/api');
curl_setopt_array($ch, array(
  CURLOPT_POST => TRUE,
  CURLOPT_RETURNTRANSFER => TRUE,
  CURLOPT_HTTPHEADER => $headers,
  CURLOPT_POSTFIELDS => json_encode($some_data),
  CURLOPT_HEADER => 1
));
// Send the request
$response = curl_exec($ch);
list($header, $body) = explode("\r\n\r\n", $response, 2);

$result = json_decode($body);

这可能是什么原因?

1 个答案:

答案 0 :(得分:1)

好的,所以解决方案在我的情况下很简单:PDO连接使用了错误的字符集。 (API从数据库中检索了有问题的字符串,但未正确编码)愚蠢的错误