Search code examples
phpjsoncurlfopenmeetup

Get Meetup events data through meetup open events live stream in php


I am trying to get meetup events data through meetup open event stream API.

http://www.meetup.com/meetup_api/docs/stream/2/open_events/

I am using the following code for get data:

// Open a stream in read-only mode
if (!($stream = fopen("http://stream.meetup.com/2/open_events", 'r'))) {
    die('Could not open stream for reading');
}

// Check if the stream has more data to read
while (!feof($stream)) {
    // Read 1024 bytes from the stream
    $data= fread($stream, 1024);

    echo '<pre>';
    echo ($data);
}
// Be sure to close the stream resource when you're done with it
fclose($stream);
exit;

The above code is returning results and data is in json format and then I have to decode it. I can decode it with php 'json_decode' function. But the problem I am facing is that I have receiving json objects data some time full object and sometimes half objectthat can not be decode in php.

Any help with my code or other code sample can be very helpful and thankful.


Solution

  • The problem is likely

    fread($stream, 1024);
    

    If the JSON is longer than those 1024 bytes, you get broken objects. Either increase the length or use fgets without a length argument instead or use this somewhat shorter alternative:

    $stream = new SplFileObject("http://stream.meetup.com/2/open_events");
    while (!$stream->eof()) {
        var_dump(json_decode($stream->fgets()));
    }