简体   繁体   English

用PHP curl post / put编码

[英]Encoding in PHP curl post/put

I'm trying to send JSON via curl in PHP to a REST web service. 我正在尝试通过PHP中的curl将JSON发送到REST Web服务。 It works fine when I am using English letters, but I'm getting errors for some international characters. 当我使用英文字母时,它工作正常,但某些国际字符出现错误。

For some characters, such as Ð, ð and ó, I don't get an error, but when I look at the final product (I'm transmitting data to another database), the letters have been replaced by question marks. 对于某些字符,例如Ð,ð和ó,我没有收到错误消息,但是当我查看最终产品(我正在将数据传输到另一个数据库)时,字母已被问号代替。 Só " Óli " becomes " ?li " Só“ Óli ”成为“ ?li

For other characters, such as Þ, I get a 500 error from the web service: "No mapping for the Unicode character exists in the target multi-byte code page" 对于其他字符,例如Þ,我从Web服务中收到500错误:“目标多字节代码页中不存在Unicode字符的映射”

When I try to use iconv, utf8_encode, utf8_decode or mb_convert_encoding and then use curl, I get the same error as with Þ. 当我尝试使用iconv,utf8_encode,utf8_decode或mb_convert_encoding然后使用curl时,我得到的错误与Þ相同。

In case, you are wondering, the other database does allow international characters (I am able to type them directly into the database and/or upload with CSV). 如果您想知道,其他数据库确实允许使用国际字符(我可以直接将其输入数据库和/或使用CSV上载)。

I've tried adding curl_setopt( $curl, CURLOPT_ENCODING, "" ); 我试过添加curl_setopt( $curl, CURLOPT_ENCODING, "" ); and curl_setopt( $curl, CURLOPT_ENCODING, "UTF-8" ); curl_setopt( $curl, CURLOPT_ENCODING, "UTF-8" ); to the curl. 卷曲。

I've tried adding header('Content-Type: text/html; charset=utf-8'); 我尝试添加header('Content-Type: text/html; charset=utf-8'); to the php file (not sure if this has any impact on curl or if it only impacts how it displays in the browser). 到php文件(不确定是否会对curl产生任何影响,或者仅影响它在浏览器中的显示方式)。

$json = '
{ 
"CardUniqueId": "1",
"PersonName": "Þæö"
}';

$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_URL, $uri . $action);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('api-key: '. $apikey));
curl_setopt( $curl, CURLOPT_ENCODING, "" ); 
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($curl, CURLOPT_POSTFIELDS,$json);
curl_setopt($curl,CURLOPT_POST, 1);
$resp = curl_exec($curl);
curl_close($curl);

Is there anything I am forgetting? 我有什么要忘的吗?

Note: I think I have done this before using the same curl settings, without problems, but it's been a while, so I might be mistaken. 注意:我想我已经在使用相同的curl设置之前完成了此操作,没有问题,但是已经有一段时间了,所以我可能会误会。 But I mention that because there is a chance the owner of the web service has made some changes on their end, causing this problem. 但我提到这是因为Web服务的所有者有可能在其端进行了一些更改,从而导致了此问题。

You're forgetting that JSON is a data transfer format, and not just a string. 您忘记了JSON是一种数据传输格式,而不仅仅是一个字符串。 Use appropriate tools when working with it: 使用它时,请使用适当的工具:

$data = ["CardUniqueId" => 1, "PersonName" => "Þæö"];
$json = json_encode($data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM