简体   繁体   中英

Getting JSON response with PHP

I'm trying to connect an API that uses 0AUTH2 via PHP. The original plan was to use client-side JS, but that isn't possible with 0AUTH2.

I'm simply trying get a share count from the API's endpoint which is here: https://api.bufferapp.com/1/links/shares.json?url=[your-url-here]&access_token=[your-access-key-here]

I do have a proper access_token that I am using to access the json file, that is working fine.

This is the code I have currently written, but I'm not even sure I'm on the right track.

// 0AUTH2 ACCESS TOKEN FOR AUTHENTICATION
$key = '[my-access-key-here]';

// JSON URL TO BE REQUESTED
$json_url = 'https://api.bufferapp.com/1/links/shares.json?url=http://bufferapp.com&access_token=' . $key;

// GET THE SHARE COUNT FROM THE REQUEST
$json_string = '[shares]';

// INITIALIZE CURL
$ch = curl_init( $json_url );


// CONFIG CURL OPTIONS
$options = array(
    CURLOPT_RETURNTRANSFER  => true,
    CURLOPT_HTTPHEADER      => array('Content-type: application/json') ,
    CURLOPT_POSTFIELDS      => $json_string
);

// SETTING CURL AOPTIONS
curl_setopt_array( $ch, $options );

// GET THE RESULTS
$result =  curl_exec($ch); // Getting jSON result string

Like I said, I don't know if this is the best method - so I'm open to any suggestions. I'm just trying to retrieve the share count with this PHP script, then with JS, spit out the share count where I need it on the page.

My apologies for wasting anyone's time. I have since been able to work this out. All the code is essentially the same - to test to see if you're getting the correct response, just print it to the page. Again, sorry to have wasted anyones time.

<?php

// 0AUTH2 ACCESS TOKEN FOR AUTHENTICATION
$key    = '[your_access_key_here]';

// URL TO RETRIEVE SHARE COUNT FROM
$url = '[your_url_here]';

// JSON URL TO BE REQUESTED - API ENDPOINT
$json_url = 'https://api.bufferapp.com/1/links/shares.json?url=' . $url . ' &access_token=' . $key;

// GET THE SHARE COUNT FROM THE REQUEST
$json_string = '[shares]';

// INITIALIZE CURL
$ch = curl_init( $json_url );

// CONFIG CURL OPTIONS
$options = array(
    CURLOPT_RETURNTRANSFER  => true,
    CURLOPT_HTTPHEADER      => array('Content-type: application/json') ,
    CURLOPT_POSTFIELDS      => $json_string
);

// SETTING CURL AOPTIONS
curl_setopt_array( $ch, $options );

// GET THE RESULTS
$result =  curl_exec($ch); // Getting jSON result string

print $result;


?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM