Page 1 of 1

How to grab individual fields from an API call?

Posted: Mon Nov 20, 2017 7:25 am
by 2Charlie
I'm new to API call and retrieving individual fields. This is an example of the API call page.

Code: Select all

public function updateArticleHtml()
{
    $agent 	= "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)";
    $projectID 	= "{{123456789021}}";
    $endPoint	= "https://app.knowledgeowl.com/api/head/article?project_id={$projectID}&status=published";
    $postparams = array();
    $postparams['_authbykey'] = "{{123456789132}}";
    $postparams['_fields'][] = 'current_version'; //if not specified will return all fields
    $postparams = http_build_query($postparams);
    
    //pull back the article html and update
    $ch=curl_init();
    curl_setopt($ch, CURLOPT_URL, $endPoint . '?' . $postparams);
    curl_setopt($ch, CURLOPT_NOPROGRESS, 1);  
    curl_setopt($ch, CURLOPT_VERBOSE, 0);  
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);  
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_USERAGENT, $agent);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    
    $buffer = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);
    
    if(!empty($error))
    {
        //handle error
    }
    
    $json = json_decode($buffer, true);
    if(!$json['valid'])
    {
        //handle error
    }
    else
    {
        $currentHTML = $json['data']['current_version']['en']['text'];
        
        //update text
        $updatedHTML = str_replace('some string', 'some new string', $currentHTML);
    }
    
    //push the updated html back into the article
    $postparams = array();
    $postparams['_authbykey'] = "{{API KEY}}";
    $postparams['current_version']['en']['text'] = $updatedHTML;
    $postparams['_method'] = 'PUT';
    $postparams = http_build_query($postparams);
    
    //pull back the article html and update
    $ch=curl_init();
    curl_setopt($ch, CURLOPT_URL, $endPoint . '?' . $postparams);
    curl_setopt($ch, CURLOPT_NOPROGRESS, 1);  
    curl_setopt($ch, CURLOPT_VERBOSE, 0);  
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);  
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_USERAGENT, $agent);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$postparams);
    
    $buffer = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);
    
    if(!empty($error))
    {
        //handle error
    }
    
    $json = json_decode($buffer, true);
    if(!$json['valid'])
    {
        //handle error
    }
    else
    {
        //article updated successfully
    }
}
At this point, I'm not updating the article. Once all the articles are pulled, how do I go through each article and grab individual fields and store it in my MySQL database? For example, the fields are ID, title, name, summary, status, url_has etc..

Here's what the data returned looks like.

Code: Select all

{
valid: true,
page_stats:
{
total_records: 2603,
total_pages: 6,
next_page: 2
},
data: [
    {
        id: "572ba7f3321342521cf2c72a",
        type: "article",
        summary: "",
        project_id: "55c4ffd131254c527e294fe6",
        name: "Student Test #1",
        searchTitle:
        {
            en: "Student Test 1"
        },
        toc_title: "",
        internal_title: null,
        languages: null,
        current_version:
        {
            en:
            {
                ⁃ title: "Student Test #1",
                ⁃ text: "<p>blah blah bleee blaah</p> "
            }
        },
        visibility: "public",
        view_count: null,
        category: "",
        application_screens:
        [
            ""
        ],
        current_version_id: "572ba7fd99876c0f4dc15aaf",
        current_version_number: 1,
        date_created: "05/05/2016 3:07 pm CDT",
        date_modified: "05/05/2016 3:09 pm CDT",
        date_published: null,
        date_deleted: null,
        modified_author: "55c5006132131cc87f294f75",
        status: "deleted",
        index: 0,
        category_view: "",
        prevent_searching: "",
        hide_from_toc: "",
        remove_pdf: "",
        remove_feedback: "",
        remove_comments: "",
        url_hash: "student-test-1",
        callout: "none",
        callout_expire: 1463083766,
        callout_video: "",
        auto_save:
            {
                time: 1462493400,
                authorID: "55c50062345641cc87f294f75",
                content: "<p>blah blah bleee blaah</p> "
            },
        reader_roles: "",
        inherited_roles: null,
        pdf: "/help/pdfexport/id/572ba7f332431c521cf2c72a",
        related_articles:
           [
                ""
            ],
        content_article: null,
        article_link: null,
        redirect_link: null,
        author: "55c5006132131cc87f294f75",
        user_teams: "",
        tags: "",
        search_phrases: "",
        ready_versions: null,
        parents:
            [
                "572ba77c332541cda1bf2c72d"
            ],
        meta_data: null,
        meta_description: null,
        meta_page_title: null,
        template_article: null,
        topic_article: null
    },
Thank you.

Re: How to grab individual fields from an API call?

Posted: Mon Nov 20, 2017 9:02 am
by requinix
You have the decoded JSON in $json. Do a loop over the appropriate subarray (what you posted isn't indented so it's hard to tell what that would be) and execute whatever queries you need to store the values.

Re: How to grab individual fields from an API call?

Posted: Mon Nov 20, 2017 9:33 am
by 2Charlie
Awesome! Thank you. I'l give try the loop and see what I get. By the way, since I don't plan on updating, I can ignore these codes from the API example, correct?

Code: Select all

//push the updated html back into the article
    $postparams = array();
    $postparams['_authbykey'] = "{{API KEY}}";
    $postparams['current_version']['en']['text'] = $updatedHTML;
    $postparams['_method'] = 'PUT';
    $postparams = http_build_query($postparams);
    
    //pull back the article html and update
    $ch=curl_init();
    curl_setopt($ch, CURLOPT_URL, $endPoint . '?' . $postparams);
    curl_setopt($ch, CURLOPT_NOPROGRESS, 1);  
    curl_setopt($ch, CURLOPT_VERBOSE, 0);  
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);  
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_USERAGENT, $agent);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$postparams);
    
    $buffer = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);
    
    if(!empty($error))
    {
        //handle error
    }
    
    $json = json_decode($buffer, true);
    if(!$json['valid'])
    {
        //handle error
    }
    else
    {
        //article updated successfully
    }

Re: How to grab individual fields from an API call?

Posted: Mon Nov 20, 2017 9:49 am
by requinix
You can ignore it if it is not relevant to you. Since that code queries the API it's kinda important, but if you understand what to do then you can write your own code using the example as a reference.

Re: How to grab individual fields from an API call?

Posted: Mon Nov 20, 2017 11:08 pm
by Christopher
2Charlie wrote:Awesome! Thank you. I'l give try the loop and see what I get.
With decoded JSON, it is something good to look at the result to see how to traverse. To see what PHP data structures are generated, do something like:

Code: Select all

$json = json_decode($buffer, true);
echo "<pre>" . print_r($json, 1) . "</pre>";

Re: How to grab individual fields from an API call?

Posted: Tue Nov 21, 2017 9:06 am
by 2Charlie
So, here's what I have.

Code: Select all

$json = json_decode($buffer, true);
    if(!$json['valid'])
    {
        //handle error
    }
    else
    {
       $currentHTML = $json['data']['url_hash'];
       var_dump($currentHTML);
    }
This outputs NULL instead of the data. If I have just $currentHTML = $json['data']; then it shows a bunch of data. So, the question is, how do I output fields that are nested?

Re: How to grab individual fields from an API call?

Posted: Tue Nov 21, 2017 9:52 am
by requinix

Code: Select all

data: [
The data is an array. A regular array that doesn't have string keys, that is. So you'll need a loop...

Re: How to grab individual fields from an API call?

Posted: Tue Nov 21, 2017 10:10 am
by 2Charlie
So, I tried this:

Code: Select all

$arr_length = count($json);
for($i=0; $i<$arr_length; $i++)
{
    $currentHTML = $json['data'].['searchTitle'].['en'];
    echo "<pre>".print_r($currentHTML)."</pre>";
}
And this is what it print out:

ArrayArrayArray
1
ArrayArrayArray
1
ArrayArrayArray
1


Am I missing something?

Re: How to grab individual fields from an API call?

Posted: Tue Nov 21, 2017 7:49 pm
by requinix
Missing quite a bit, yes.

How familiar are you with PHP? Done much work with it? Do you know how to use arrays and loops and stuff?

Re: How to grab individual fields from an API call?

Posted: Wed Nov 22, 2017 10:42 am
by Christopher
I'd recommend starting with the following to see what you actually have:

Code: Select all

echo "<pre>".print_r($json)."</pre>";
Am I missing something?
Remember, this is PHP not Javascript. The code $json['data'].['searchTitle'].['en'] is using the . concatenation operator and ['searchTitle'] and ['en'] are array literals -- each with one string element.

If $json is an object, you would access 'data' with $json->data

If $json is an array with element 'data', you would access it with $json['data']

Likewise, if $json->data is an object, it would be $json->data->searchTitle otherwise if it's an array then $json->data['searchTitle'] and so on...