Getting Twitter followers with JSON in PHP? - php

I can get Tweets of users quite easily using PHP and JSON, but as soon as I use it to get a list of followers, I get errors. Both use JSON to return the values.
The code is:
$jsonurl = "https://api.twitter.com/1/followers/ids.json?cursor=-1&screen_name=mooinooicat";
$contents = file_get_contents($jsonurl);
$results = json_decode($contents, true);
echo "<pre>";
print_r($results);
echo "</pre>";
This gives me the following array:
Array
(
[next_cursor] => 0
[ids] => Array
(
[0] => 31085924
[1] => 53633023
[2] => 18263583
)
[previous_cursor] => 0
[next_cursor_str] => 0
[previous_cursor_str] => 0
)
How do I get the values of next_cursor and previous_cursor and how do I loop just through the ids array?
I want to parse the results for reading into a database.

you are not using the correct api try something like this
function fetch_twitter_count($user) {
if ($json = file_get_contents("http://api.twitter.com/1/users/show.json?screen_name=$user")) {
if(empty($json)) return 0;
$json = json_decode($json['body'], true);
return number_format(intval($json['followers_count']));
}
return 'API Error';
}
have not tested but should do what you want however keep inmind that you will want to use some sort of caching

Thanks for all the answers without examples...
I finally managed to figure it out using the example from Getting values from a single array
Here is the code:
foreach ( $results as $result ) {
if ( is_array( $result ) ) {
foreach ( $result as $sub_result ) {
// You can store this value in a variable, or output it in your desired format.
echo $sub_result . "<br />";
}
} else {
echo $result . "<br />";
}
}

Related

how to get individual value from array list in wordpress with php

I want to get a single value from the array in PHP, Wordpress, I have tried more code, but I am unable to get the values. I have given below using my code. Please help me anyone and save me.
$result = $wpdb->get_results("SELECT * FROM wp_confirmation WHERE user_id=$user_id");
if($result)
{
foreach ( $result as $print )
{
echo $cand[0]->['Cand'];
}
}
This is my array values
Array ( [0] => stdClass Object ( [id] => 100 [comment] => wait for the moment
[Cand] => Dossier incomplet [candConfdate] => 2020-01-03
[datetrapedaCand] => 2020-01-09
$result = $wpdb->get_results("SELECT * FROM wp_confirmation WHERE user_id=$user_id");
if($result)
{
foreach ( $result as $print )
{
echo $print->Cand;
echo $print-> comment;
}
}
You can get all individual value according to above example
$result = $wpdb->get_results("SELECT * FROM wp_confirmation WHERE user_id=$user_id");
if ($result) {
foreach ($result as $print) {
//$print is object, use -> to access properties of the object.
echo $print->id;
echo $print->comment;
echo $print->Cand;
echo $print->candConfdate;
echo $print->datetrapedaCand;
}
}

Not updating data on json file but my code is correct via PHP

I'm a newbie here so please be with. I'm pretty sure that my code and syntax is correct.
This is my json file
{"data":
[
{"label":"Signed-in Client","value":2
}
]
}
This is my php code
<?php
$conn=mysqli_connect("localhost", "root","","something");
$res1 = mysqli_query($conn, "SELECT * FROM tbl_pet_owner ORDER BY pet_owner_id");
$max1 = mysqli_num_rows($res1);
$jsonString = file_get_contents('data.json');
$data1 = json_decode($jsonString, true);
foreach ($data1['data'] as $key )
{
if ($key[0]['label'] == "Signed-in Client")
{
$data1['value'] = $max1;
}
}
$newJsonString = json_encode($data1);
file_put_contents('data.json', $newJsonString);
?>
but when I refresh, it doesn't update with the max count of my query. I hope you'd help me. This is for my thesis
It seems to me that the problem is connected with the way how you traverse the data.
For example in foreach ($data1['data'] as $key ), $key is already an associative array (e.g., array("label" => "Signed-in Client", "value" => 2)), so instead of $key[0]['label'], one should use just $key['label'].
Also, when you want to modify the 'value', one has to access the same associative array, not the original variable $data1.
One way to achieve this would be as shown below. In that example the array $data1['data'] is traversed using references (&$key). Note that one should then unset this variable after the foreach block to break its association with the last element of the array being traversed.
<?php
$max1 = 100;//just an example
$jsonString = file_get_contents('data.json');
$data1 = json_decode($jsonString, true);
foreach ($data1['data'] as &$key )
{
print_r($key);
if($key['label'] == "Signed-in Client")
{
$key['value'] = $max1;
}
}
unset($key);
print_r($data1);
/* gives:
Array
(
[data] => Array
(
[0] => Array
(
[label] => Signed-in Client
[value] => 100
)
)
)
*/
//$newJsonString = json_encode($data1);
//file_put_contents('data.json', $newJsonString);
?>

MySql PHP Select JSON value

I have this SQL query.
$sql = "SELECT playerjson FROM `clans` WHERE playercount > ? AND level > ? AND score > ?";
$selectstmt = $con->prepare($sql);
$selectstmt->bind_param('iii',$playercountvar,$levelvar,$scorevar);
$selectstmt->execute(); //execute select statement
$result = $selectstmt->get_result(); //get select statement results
playerjson is a large JSON Array.
[
{
"avatar":{
"userId":253404325847,
"currentHomeId":253404325847,
"userName":"enal",
"role":"Member",
"level":62,
"league":8,
"trophies":1707,
"donatedTroops":0,
"receivedTroops":0,
"clanRank":1,
"lastClanRank":2,
"inWar":1
}
},
{
"avatar":{
"userId":158925253577,
"currentHomeId":158925253577,
"userName":"Valen kamja",
"role":"Leader",
"level":54,
"league":8,
"trophies":1693,
"donatedTroops":1054,
"receivedTroops":2131,
"clanRank":2,
"lastClanRank":3,
"inWar":1
}
},
{
"avatar":{
"userId":296357929514,
"currentHomeId":296357929514,
"userName":"\u0645\u064c\u0648\u0646\u0633\u062a\u064d\u0631502",
"role":"Member",
"level":59,
"league":7,
"trophies":1568,
"donatedTroops":0,
"receivedTroops":0,
"clanRank":3,
"lastClanRank":0,
"inWar":1
}
},
{
"avatar":{
"userId":283468864924,
"currentHomeId":283468864924,
"userName":"tolzz",
"role":"Co-Leader",
"level":64,
"league":7,
"trophies":1312,
"donatedTroops":34,
"receivedTroops":456,
"clanRank":4,
"lastClanRank":4,
"inWar":1
}
},
{
"avatar":{
"userId":257703167804,
"currentHomeId":257703167804,
"userName":"hailery",
"role":"Co-Leader",
"level":58,
"league":6,
"trophies":1219,
"donatedTroops":21,
"receivedTroops":404,
"clanRank":5,
"lastClanRank":5,
"inWar":1
}
},
{
"avatar":{
"userId":210456177319,
"currentHomeId":210456177319,
"userName":"chey lie",
"role":"Co-Leader",
"level":79,
"league":0,
"trophies":1101,
"donatedTroops":0,
"receivedTroops":0,
"clanRank":6,
"lastClanRank":6,
"inWar":0
}
}
]
What I want to do is just store the userid and currenthomeid and store them in an array which will be in a parent array...
Because from that I will need to get the child array and pass those one by one as parameters in a url. explode wouldn't work with this would it?
How would I go about achieving this? Also I need a way to improve the SQL Statement so that I don't retrieve the entire JSON like that as it could take longer?
Decode the result string and iterate over it as stdClasses :
$json = json_decode($result);
$parent = array();
foreach($json as $item) {
$parent[] = array('userId' => $item->avatar->userId, 'currentHomeId' => $item->avatar->currentHomeId);
}
echo '<pre>';
print_r($parent);
echo '</pre>';
will produce :
Array
(
[0] => Array
(
[user] => 253404325847
[currentHomeId] => 253404325847
)
[1] => Array
(
[user] => 158925253577
[currentHomeId] => 158925253577
)
etc. To pass $parent as a URL string you could simply use json_encode to stringify it :
$url = '?values='.json_encode($parent);
gives ?values=[{"user":253404325847,"currentHomeId":253404325847},{"user":158925253577," etc...
This will automatically be escaped, you can read the array back in javascript clientside with
var value = window.location.href.split('?values=')[1],
array = JSON.parse(unescape(value));
console.log(array);
you now have the array as JSON objects clientside. There is many ways you could do this. This was just a quick suggesion.
What you have is a json encoded atrray. So use json_decode() to decode it.
$arr1 = json_decode($result);
foreach ($arr1 as $row) {
echo $row->avatar->userId."-------".$row->avatar->currentHomeId."<br>" ;
}

Storing values of multidimensional array into variables

I have the following code:
$res = $db->getArticles($db);
$hey = print_r($res, TRUE);
echo $hey['0'];
Here is the code for $db->getArticles:
public function getArticles() {
$array = array();
try {
$sth = $this->db->prepare("SELECT * FROM posts ORDER BY id");
$sth->execute();
foreach ($sth->fetchAll(PDO::FETCH_ASSOC) as $row) {
$array[] = $row;
}
return $array;
} catch (Exception $e) {
}
}
The logic is that the function queries the database and puts everything into an array. The number of rows in the table will always be pretty low, so performance isn't an issue.
The following is the output of the first code snippet above:
echo $hey['0']; // prints "A" (without the quotes).
echo $hey['1']; // prints "r"
echo $hey['2']; // prints "r"
echo $hey['3']; // prints "a"
echo $hey['4']; // prints "y"
As you can see, it spells out the word "Array."
echo $hey prints the following:
Array ( [0] => Array ( [id] => 1 [author] => 0 [content] => This Is a Test [publication_date] => 1380380992 ) )
My end goal is to store each individual value into a variable and do something with it. This would all happen inside a for loop which runs on the array so I can get information from each row.
What am I doing wrong?
$hey = print_r($res, TRUE);
This will return a string that gives the info of the array $res. If you echo it, you should expect to see the same as what print_r($res); displays, as you've shown. $res is already an array of your query data, so loop over that.
foreach($res as $row) { //row loop
foreach($row as $col) { //column loop
//do something
}
}
$array = array( array( ID => 1,
author => 0,
content => "This Is a Test",
publication_date => 1380380992
)
);
echo $array['0']['author'];
This works for me...
just echo echo $array['0']['author']; and replace author by the field you need.

Iterating part of array causes error

I have some Json being returned from facebook which I'm then parsing in to an array using json _decode. The data ends up looking like this (this is just the snippet I'm interested in):
( [data] =>
Array ( [0] =>
Array (
[id] => 1336269985867_10150465918473072
[from] =>
Array ( [name] => a name here
[category] => Community
[id] => 1336268295867 )
[message] => A message here
Now I've been able to iterate over this data and get what I need:
$jsonDecoded = json_decode($json, true);
$xmlOutput = '<?xml version="1.0"?><data><items>';
foreach ($jsonDecoded as $e) {
foreach ($e as $i) {
$xmlOutput .= '<item><timestamp>' . $i['created_time'] . '</timestamp><title><![CDATA[ ' . $i['message'] .' ]]></title><link>' . $link . '</link><type>facebook</type></item>';
}
}
$xmlOutput .= '</items></data>';
..up until now where I need to check on the from->id value.
I added this line in the second for each:
foreach ($e as $i) {
if($i['from']['id'] == '1336268295867') {
But this just gives me an error:
Fatal error: Cannot use string offset as an array in /Users/Desktop/Webs/php/getFeeds
Any ideas why? I'm sure this is the correct way to get at that value and in actual fact if I echo this out in my loop instead of doing the if statement above I get the value back:
$jsonDecoded = json_decode($json, true);
$xmlOutput = '<?xml version="1.0"?><data><items>';
foreach ($jsonDecoded as $e) {
foreach ($e as $i) {
echo $i['from']['id']
This returns me all of the from->id values in the code returned from facebook and then following this I get the error:
133626829985867133626829985867133626829985867133626829985867195501239202133626829985867133626829985867133626829985867133626829985867133626829985867
Fatal error: Cannot use string offset as an array in /Users/Desktop/Webs/php/getFeeds.php on line 97
(line 97 is the echo line)
Your code makes a lot of assumptions about $i['from']['id'] and at least one of them is incorrect for at least one entry.
Let's add some tests:
$jsonDecoded = json_decode($json, true);
$xmlOutput = '<?xml version="1.0"?><data><items>';
foreach ($jsonDecoded as $e) {
if ( !is_array($e) ) {
die('type($e)=='.gettype($e).'!=array');
}
foreach ($e as $i) {
if ( !is_array($i) ) {
die('type($i)=='.gettype($i).'!=array');
}
else if ( !array_key_exists('from', $i) ) {
die('$i has no key "from"');
}
else if ( !is_array($i['from']) ) {
die('type($i["from"])=='.gettype($i['from']).'!=array');
}
else if ( !array_key_exists('id', $i['from']) ) {
var_dump($i);
die('$i["from"] has no key "id"');
}
echo $i['from']['id'];
}
}
And then you can add a var_dump(...) before the die(...) to take a look at the actual data.
It seems to me that (according to the last code snippet) at some point your $i is not an array anymore. Try to do:
$jsonDecoded = json_decode($json, true);
$xmlOutput = '<?xml version="1.0"?><data><items>';
foreach ($jsonDecoded as $e) {
foreach ($e as $i) {
if(is_array($i))
echo $i['from']['id']

Categories