1

I am accessing API for "ConnectWise". the data comes into JSON format. i was able to parse the data into table via PHP. however, empty fields in JSON results in Undefined index. This happens for some items with no website, or address for example. the rest shows up fine. Any help or input would be appreciated.

Here is my code to get the data from Connectwise:

function get_companies(){

   $curl = curl_init();
   curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 1);
   curl_setopt($curl, CURLOPT_URL, "https://api- 
   na.myconnectwise.net/v4_6_release/apis/3.0/company/companies");
   curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1 );
   curl_setopt($curl, CURLOPT_HTTPHEADER, array(

  "Authorization: Basic (OUR KEY)",

   'Content-type: application/json'

       ));

$result = curl_exec($curl);
curl_close($curl);
$decoded =  json_decode($result,true);
return $decoded;
}

And to display the data:

function list_all_accounts(){

    $accounts = get_companies();

    if ( !empty ($accounts)){
            foreach ($accounts as $account) {

                {
        echo "
                    </td>
                    <td>
                        $account[id]
                    </td>
                    <td>
                        $account[name]
                    </td>
                    <td>
                        $account[addressLine1]
                    </td>
                    <td>
                         $account[phoneNumber]
                    </td>
                    <td>
                         $account[website]
                    </td>   
                    <td>
                        $account[name]
                    </td>                       
                    </tr>";
            }
    }
   }
 }

Update - Json Sample

    [
    {
        "id": 250,
        "identifier": "company name ",
        "name": "company name",
        "status": {
            "id": 1,
            "name": "Active",
            "_info": {
                "status_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/statuses/1"
            }
        },
        "type": {
            "id": 1,
            "name": "Client",
            "_info": {
                "type_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/types/1"
            }
        },
        "addressLine1": "address line 1",
        "city": "New York",
        "state": "NY",
        "zip": "11111",
        "country": {
            "id": 1,
            "name": "United States",
            "_info": {
                "country_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/countries/1"
            }
        },
        "phoneNumber": "123456789",
        "faxNumber": "",
        "website": "www.site.com",
        "territoryId": 2,
        "accountNumber": "",
        "dateAcquired": "2006-06-21T04:00:00Z",
        "sicCode": {
            "id": 1209,
            "name": "consulting"
        },
        "annualRevenue": 0,
        "timeZone": {
            "id": 1,
            "name": "GMT-5/Eastern Time: US & Canada",
            "_info": {
                "timeZoneSetup_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/system/timeZoneSetups/1"
            }
        },
        "leadFlag": false,
        "unsubscribeFlag": false,
        "userDefinedField5": "1",
        "taxCode": {
            "id": 8,
            "name": "Tax-State",
            "_info": {
                "taxCode_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/finance/taxCodes/8"
            }
        },
        "billingTerms": {
            "id": 1,
            "name": "Net 30 days"
        },
        "billToCompany": {
            "id": 250,
            "identifier": "comp1 ",
            "name": "company1.",
            "_info": {
                "company_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/250"
            }
        },
        "billingSite": {
            "id": 1291,
            "name": "company1",
            "_info": {
                "site_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies"
            }
        },
        "invoiceDeliveryMethod": {
            "id": 1,
            "name": "Mail"
        },
        "deletedFlag": false,
        "mobileGuid": "1df91371-6d7a-4778-ab81-f3e7761f5211",
        "currency": {
            "id": 7,
            "symbol": "$",
            "isoCode": "USD",
            "name": "US Dollars",
            "_info": {
                "currency_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/finance/currencies/7"
            }
        },
        "_info": {
            "lastUpdated": "2018-04-02T16:36:05Z",
            "updatedBy": "user1",
            "dateEntered": "2006-06-21T16:04:59Z",
        }
    },
     {
        "id": 250,
        "identifier": "company name ",
        "name": "company name",
        "status": {
            "id": 1,
            "name": "Active",
            "_info": {
                "status_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/statuses/1"
            }
        },
        "type": {
            "id": 1,
            "name": "Client",
            "_info": {
                "type_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/types/1"
            }
        },
        "addressLine1": "address line 1",
        "city": "New York",
        "state": "NY",
        "zip": "11111",
        "country": {
            "id": 1,
            "name": "United States",
            "_info": {
                "country_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/countries/1"
            }
        },
        "phoneNumber": "123456789",
        "faxNumber": "",
        "website": "www.site.com",
        "territoryId": 2,
        "accountNumber": "",
        "dateAcquired": "2006-06-21T04:00:00Z",
        "sicCode": {
            "id": 1209,
            "name": "consulting"
        },
        "annualRevenue": 0,
        "timeZone": {
            "id": 1,
            "name": "GMT-5/Eastern Time: US & Canada",
            "_info": {
                "timeZoneSetup_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/system/timeZoneSetups/1"
            }
        },
        "leadFlag": false,
        "unsubscribeFlag": false,
        "userDefinedField5": "1",
        "taxCode": {
            "id": 8,
            "name": "Tax-State",
            "_info": {
                "taxCode_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/finance/taxCodes/8"
            }
        },
        "billingTerms": {
            "id": 1,
            "name": "Net 30 days"
        },
        "billToCompany": {
            "id": 250,
            "identifier": "comp1 ",
            "name": "company1.",
            "_info": {
                "company_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/250"
            }
        },
        "billingSite": {
            "id": 1291,
            "name": "company1",
            "_info": {
                "site_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies"
            }
        },
        "invoiceDeliveryMethod": {
            "id": 1,
            "name": "Mail"
        },
        "deletedFlag": false,
        "mobileGuid": "1df91dd371-6d7addd-4778s-ab81-f3e7761f5211",
        "currency": {
            "id": 7,
            "symbol": "$",
            "isoCode": "USD",
            "name": "US Dollars",
            "_info": {
                "currency_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/finance/currencies/7"
            }
        },
        "_info": {
            "lastUpdated": "2018-04-02T16:36:05Z",
            "updatedBy": "user1",
            "dateEntered": "2006-06-21T16:04:59Z",
            "enteredBy": "CONVERSION",
        }
    }
]
Nah
  • 1,690
  • 2
  • 26
  • 46
Blazion
  • 21
  • 2
  • Some sample JSON data that causes the error would be helpful... – Nick May 12 '18 at 03:12
  • 1
    Possible duplicate of [PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"](https://stackoverflow.com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef) – Spoody May 12 '18 at 03:18
  • Updated with a sample JSON – Blazion May 12 '18 at 03:19
  • Does this exact JSON cause the error? It looks like all the keys you're referencing are present in both records here, so if this input is causing those errors, then your main problem would seem to be somewhere else. (Not that there's no problems with your code...) – Greg Schmidt May 12 '18 at 03:31
  • @GregSchmidt - yes that the same one, the first 2 at least. the error happens if one of the field "website" for example is empty. it shows "Website": "", – Blazion May 12 '18 at 03:35
  • But both of the records shown have websites, hence why I was asking if *this exact JSON* causes the error. Anyway, the page @Mehdi linked to should be of some help. – Greg Schmidt May 12 '18 at 03:40
  • `json_decode()` and https://jsonlint.com/ both complain about the comma after the value on lines 95 and 194. Removing them makes it valid json which should fix your issue, but the question becomes why is it showing up in your data feed from your API? Or were those 2 introduced via copy/paste on your end? – ivanivan May 12 '18 at 03:42
  • @ivanivan - this is a what shown from the API. the data is huge, i editted some items as they are our clients data. so i may have made a mistake. However - assuming one of the 2 provided was without property for "website" for example, it would through the error. – Blazion May 12 '18 at 03:44
  • looking at the linked post - i was able to overcome the error using ` $website = array_key_exists('website', $account) ? $account['website'] : ''; ` and echo $website. however, now that i have a long list of items, is there an easy way to run array_key_exists on all items in the array? – Blazion May 13 '18 at 04:14

2 Answers2

0

json_decode() and https://jsonlint.com/ both complain about the comma after the value on lines 95 and 194. Removing them makes it valid json, after which your code works as soon as you remember to quote the key values for the associative array.

I removed the two offending commas in the json and saved as a file, then added the quoting for your key values on the array, and finally removed the HTML table stuff and such (I'm just running it on command line to see output). Should be easy to put back in...

<?php

function get_companies() {
    $j = file_get_contents("json.json");
    $jd = json_decode($j, true);
    return $jd;
}

$accounts = get_companies();
if (!empty($accounts)) {
    foreach ($accounts as $account) {
        echo  "\n".$account['id'] . "
              " . $account['name'] . "
              " . $account['addressLine1'] . "
              " . $account['phoneNumber'] . "
              " . $account['website'] . "
              " . $account['name']."\n\n";
    }
}
?>
ivanivan
  • 2,155
  • 2
  • 10
  • 11
0

According to your comment, it is possible that some properties that you use in your HTML are not part of the JSON you receive. This means you are accessing an array index that is not set, e.g. with $account[website].

I see two solutions for this:

  1. Only output the data if it is set in the array:

    echo '<td>'.(isset($account['website']) ? $account['website'] : '').'</td>';
    
  2. Use a an array with defaults for all the values as base for your $account array and merge them:

    $base = [
        'website' => 'no website',
        'phoneNumber' => '',
    ];
    
    foreach ($accounts as $account) {
        // this will override all elements of $base with them of $account,
        // but only if they are present in $account
        $account = array_merge($base, $account);
    
        // ... your output here ...
    }
    
Namoshek
  • 6,394
  • 2
  • 19
  • 31
  • Thanks but $account[website] shows for the items that has the property available. if the property is empty, it causes the issue. – Blazion May 13 '18 at 03:34