1

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);
2
  • Try putting $scrape in an array and then encoding. Please post a comment indicating whether this made any difference for you. Commented Sep 20, 2009 at 16:14
  • Thanks for your comment. 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) Commented Sep 20, 2009 at 18:37

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

That solved it! Now I see what crap I get back.. I can do it from here :) Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.