duanjian4331 2009-09-20 15:00
浏览 103
已采纳

使用PHP将Curl检索的HTML字符串转换为JSON,并使用AJAX

I am building a scraper with Javascript (AJAX; Prototype) and PHP (Curl). The url is served trough AJAX to the PHP/Curl.

The response is a huge HTML string. I would like to send the string in JSON to Javascript so I can process it.

If I send the raw responseText it works just fine, the html (string) get's rendered on my screen. However when I try PHP's json_encode() function, I get 'null'.

What am I doing wrong? Or is there a better way to convert the HTML string to JSON? I'm running PHP5.3, tried JSON_FORCE_OBJECT but no luck.. please help me, I have been banging my head on this one for way too long.. :(

This is the current PHP code (if I remove the json_encode function it works):

$url = $_GET['url'];

$ch = curl_init() or die(curl_error()); 

curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$scrape = curl_exec($ch) or die(curl_error()); 

echo json_encode($scrape);
echo curl_error($ch);

curl_close($ch);
  • 写回答

1条回答 默认 最新

  • dourukeng5302 2009-09-20 20:53
    关注

    Does your $scrape contain utf8 encoded string? json_encode() works only with utf8.

    Try doing

    $scrape = mb_convert_encoding($scrape, 'utf-8');
    

    before json_encode

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料