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
1 Answer
Reset to default 5Does your $scrape contain utf8 encoded string? json_encode() works only with utf8.
Try doing
$scrape = mb_convert_encoding($scrape, 'utf-8');
before json_encode