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

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

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!