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

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

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大