0

I'm trying to get a user's site_id from posterous. This data seems to be nowhere in the user's profile, and nothing in the FAQ or help or docs indicates how to find this. The only method I can find is to request a list of sites over API, So, that's what I'm trying to do, and I get back a json response, and, indeed, the site_id of any site the user has on posterous is in there, and I just want to output this.

First I tried with (where $result is the json response)

$siteid = preg_match('"site_id": \d+', $result);
echo $siteid;

I get nothing.

Then I tried with

json_decode($result);
echo $result->site_id;

I still get nothing.

I can see, in the json response ($result),

"site_id": $somenumber;

Why can't I extract this data with either preg_match or json_decode? Is there another, better method?

My full code is pasted at http://tonybaldwin.me/paste/index.php?3u

tonybaldwin
  • 171
  • 1
  • 10
  • Could you post the response you're getting from the API? – Jeroen May 09 '12 at 17:13
  • 1
    Couple things wrong with your `preg_match()` call. First, you're missing [delimiters](http://php.net/manual/en/regexp.reference.delimiters.php). Also, the function will return the number of times it matched (1 or 0), not the text that matched. With a capturing subpattern, it might work like this: `preg_match('/"site_id": (\d+)/', $result, $matches); $siteid = $matches[1];` – Wiseguy May 09 '12 at 17:21
  • The json returned looks like this: darn...too big to post in comment, pastebinned here: http://tonybaldwin.me/paste/index.php?7k – tonybaldwin May 09 '12 at 18:12
  • Aha! Thanks Wiseguy! That solved my problem. :D – tonybaldwin May 09 '12 at 18:22
  • `json_decode($result)` will return an array (not a StdClass Object), meaning you probably want to access the id with bracket notation: `echo $result['site_id']`. This should also get around the nasty business of parsing JSON with a regex :^) – rjz May 09 '12 at 23:15

1 Answers1

0

The Posterous list-of-sites API returns a list (as you might expect) of mappings. Thus, what you need to do is first pick the right item of the list, and then read it's id key.

$result = json_decode($response);
$first_result = $result[0];
$first_result_id = $first_result["id"];
echo $first_result_id;
Amber
  • 507,862
  • 82
  • 626
  • 550