最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Convert Curl retrieved HTML string to JSON with PHP, serve with AJAX - Stack Overflow

programmeradmin5浏览0评论

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);

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);
Share Improve this question asked Sep 20, 2009 at 15:00 richardrichard 14.6k8 gold badges38 silver badges41 bronze badges 2
  • Try putting $scrape in an array and then encoding. Please post a ment indicating whether this made any difference for you. – defines Commented Sep 20, 2009 at 16:14
  • Thanks for your ment. I did wat you told but it does not make any difference ($json = array(); array_push($json, $scrape); echo json_encode($json); // If I leave the json_encode out, I get 'Array' returned) – richard Commented Sep 20, 2009 at 18:37
Add a ment  | 

1 Answer 1

Reset to default 5

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

发布评论

评论列表(0)

  1. 暂无评论