1

There must be something obvious I'm doing wrong here, but I've spent hours trying to figure it out and it makes no sense.

<?php
   date_default_timezone_set('America/New_York');
   $json = file_get_contents('https://www.govtrack.us/api/v2/vote/?congress=114&chamber=house&session=2015&order_by=-created');
   $obj = json_decode( $json,true);
   $bills = $obj['objects'];

foreach($bills as $b){
    print_r($b);
    print_r($b['category']);    
    print_r($b['title']); ///wtf.   
}
 ?>

The array returned by the json request has indices for both category and title, but it returns NULL for title. Several other elements from the json array return NULL for some reason. PHP returns an undefined index error, but the index is clearly defined.

What am I missing here?

2
  • 1
    title[space] is not the same as title. make SURE that the key you think should be there really IS there. var_dump() gives you far better diagnostic information, including type/size metadata Commented Sep 30, 2015 at 19:15
  • show us the output of your print_rs. or, better yet, as @marc says, do a var_dump of all the data so we can see clearly how it is structured. Commented Sep 30, 2015 at 19:17

3 Answers 3

3

The title index is under related_bill, not the main objects array.

This should work:

foreach($bills as $b){
    print_r($b);
    print_r($b['category']);    
    print_r($b['related_bill']['title']);
}
Sign up to request clarification or add additional context in comments.

2 Comments

ARRR I can't believe I missed that. I wish var_dump or print_r would indent and add newlines to show hierarchy more clearly.
@thedownstem - It does indent. Either view the source or wrap the results in <pre> tags. That's how I worked it out! Well, that and var_dump(array_keys($obj))
2

the index is clearly defined.

No, it's not. I had a look at the URL and "title" is not an index of the objects in "objects", but of those in "related_bill"

Access it with:

$b['related_bill']['title']

Comments

1

Try this code In your json its not 'title' index but its "titles" in "related_bill"

 <?php
       date_default_timezone_set('America/New_York');
       $json = file_get_contents('https://www.govtrack.us/api/v2/vote/?congress=114&chamber=house&session=2015&order_by=-created');
       $obj = json_decode( $json,true);
       $bills = $obj['objects'];

    foreach($bills as $b){
        print_r($b);
        print_r($b['category']);    
        print_r($b['related_bill']['titles']); ///wtf.   
    }
     ?>

Replace $b['title'] with $b['related_bill']['titles']

Comments

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.