Difficulty Accessing Values from JSON Object Using PHP- Sunlight Labs congressapi
I'm trying to pull values from a JSON object pulled from the Sunlight Labs Congress API using PHP. I'm able to get request response data into a JSON object, but haven't had any success getting specific values out of the object. I can successfully dump the object using print_r.
I've been experimenting with PHP for about 12 hours now, so this is a totally n00b question...
Here's the PHP:
$zip = $_REQUEST['zip'];
$sf = new SunlightLegislator;
$data = $sf->legislatorZipCode( $zip );
$leg = json_decode($data);
echo '<pre>';
print_r($data).'</pre><p>';
echo 'First Name ';
echo $leg[1]->legislator->firstname;
echo $leg[1]->firstname;
?>
The PHP yields this output:
stdClass Object
(
[0] => stdClass Object
(
[legislator] => stdClass Object
(
[website] => http://bass.house.gov/
[fax] => 202-225-2946
[govtrack_id] => 400019
[firstname] => Charles
[chamber] => house
[middlename] =>
[lastname] => Bass
[congress_office] => 2350 Rayburn House Office Building
[eventful_id] =>
[phone] => 202-225-5206
[webform] =>
[youtube_url] =>
[nickname] => Charlie
[gender] => M
[district] => 2
[title] => Rep
[congresspedia_url] =>
[in_office] => 1
[senate_class] =>
[name_suf开发者_StackOverflow中文版fix] =>
[twitter_id] => RepCharlesBass
[birthdate] => 1952-01-08
[bioguide_id] => B000220
[fec_id] => H0NH02017
[state] => NH
[crp_id] => N00000423
[official_rss] =>
[facebook_id] =>
[party] => R
[email] =>
[votesmart_id] => 22216
)
)
[1] => stdClass Object
(
[legislator] => stdClass Object
(
[website] => http://shaheen.senate.gov
[fax] =>
[govtrack_id] => 412323
...SNIPPAGE...
[facebook_id] => SenatorShaheen
[party] => D
[email] =>
[votesmart_id] => 1663
)
)
[2] => stdClass Object
(
[legislator] => stdClass Object
(
[website] => http://ayotte.senate.gov
[fax] =>
[govtrack_id] => 412493
[firstname] => Kelly
[chamber] => senate
[middlename] => A
...SNIPPAGE...
[email] =>
[votesmart_id] => 42352
)
)
)
First Name
At the moment, I'm just trying to output the first legislator's first name to the page. I'm certain that the data's there, and doing an error check on json_decode
yields no errors. I think my trouble is in the syntax I'm using to access the decoded object.
The questions:
How would I output the a legislator's first name?
Is it possible that the website
field is breaking object access?
Thanks, Sean
This appears to be solved on stdClass Object problems by @soulmerge. For your object, the following would work:
$array = (array) $result;
$array[0]->legislator->website;
精彩评论