I'm trying to create an overlay for my twitch stream, which display not only the recent follower but a certain amount of them in chronological order.
Here a visual representation:
(Styling is done with HTML/CSS)
I've already managed to get the JSON but I don't know how to echo the names for each ['follows']['user']['display_name']
This is the API:
https://api.twitch.tv/kraken/channels/kazutode/follows?limit=5&offset=0&client_id=nht9j8w0u4xazpm1fdc2fmkrqvoici
Here's my code so far (It's not alot, basically nothing xD)
<?php
$clientID = "nht9j8w0u4xazpm1fdc2fmkrqvoici";
$channel = "kazutode";
$limit = 5;
$offset = 0;
$response = json_decode(file_get_contents('https://api.twitch.tv/kraken/channels/'.$channel.'/follows?limit='.$limit.'&offset='.$offset.'&client_id='.$clientID), true);
?>
I know, I know. I should use curl but I don't know how so I stick to json_decode.
Can someone teach me how to get the wanted data out of the ['follows'] array?
You need a foreach loop. Here is some PHP+HTML mixed to give you an idea:
$table = '';
$table .= '<table>';
foreach($response['follows'] as $entry) {
$table .= '<tr>';
$table .= '<td>'.$entry['created_at'].'</td>';
$table .= '<td>'.$entry['user']['display_name'].'</td>';
$table .= '<td><a class="your-custom-class" href="'.$entry['_links']['self'].'">View channel</a></td>';
$table .= '</tr>';
}
$table .= '</table>';
echo $table;
Related
I am trying to populate a drop-down menu with values from an array.
I have tried to follow other answers but the syntax doesn't seem to be working. (I'm still relatively new to PHP).
The following code which I am working on was produced by someone else.
$sqlite_query = "SELECT * FROM dis_kind";
$result = $db->query($sqlite_query);
$array = $result->fetchArray();
$output = "<select name=\"kind\" class=\"dis\" >\n";
$output .= "<option value=\"$this->wildcard_value\"></option>\n";
foreach ($result as $array) {
$value = $array['kind'];
$output .= "<option value=\"";
$output .= $value;
$output .= "\">";
$output .= $value;
$output .= " - ";
$output .= $array['description'];
$output .= "</option>\n";
}
$output .= "</select>\n";
I don't know why it has been done the way it has but I am stumped as to getting my drop-down to work.
Currently, the box appears but is populated with no values.
Thanks.
Eventually managed to solve the problem myself - before I pulled my hair out!
Instead of using the foreach loop, I used the following:
while($array = $result->fetchArray())
{
// Output code.
}
Which populated the drop-down with values from the array.
I have made a PHP file that takes this JSON-based file: http://www.yellowpages.com.iq/ajax/get/register/Categories.php
and converts it into an excel-formatted-table with the formatting of (.cvs) using this code :
$contents = file_get_contents('http://www.yellowpages.com.iq/ajax/get/register/Categories.php');
$data = JSON_decode($contents);
$excel_file = fopen("file.csv", "a+");
$table = "<table border='1'>";
foreach($data as $elem) {
$table .= "<tr>";
foreach($elem as $key => $prop) {
$table .= "<th>$key</th>";
$table .= "<td>$prop</td>";
fwrite($excel_file, "$key,$prop\n");
}
$table .= "</tr>";
}
$table .= "</table>";
echo $table;
But the problem being, is it takes the data and displays it correctly, although it tends to format it like so: id 1
category Advertising
id 2
category Agriculture & FoodÂ
id 3
category Air condition
id 4
category Airlines
id 5
Aluminium & Glass
Instead of what I'm trying to make it look like which I made manually:
Any help would be appreciated!
You could change the code using fputcsv, which takes care of double quotes and escaping them.
For that you need to get the JSON as an associative array (provide the second argument true):
$data = JSON_decode($contents, true);
And then the loop you have would be replaced with this:
// "loop" for the header (only 1 iteration)
foreach($data as $elem) {
$table .= "<tr><th>" . implode("</th><th>", array_keys($elem)) . "</th></tr>";
fputcsv($excel_file, array_keys($elem));
break; // only need one row for header
}
// Restart loop for the data
foreach($data as $elem) {
$table .= "<tr><td>" . implode("</td><td>", $elem) . "</td></tr>";
fputcsv($excel_file, $elem);
}
I'm generating dynamic content from a database like this:
$sql_select_items = $db->query("SELECT * FROM table WHERE ...);
Then it pulls the results, which may be one or multiple, like this:
while ($item_details = $db->fetch_array($sql_select_items))
{
$items_content =
'<table><tr> '.
'<td>RETRIEVED CONTENT HERE</td> '.
'</tr></table>';
}
Then, further down, I am outputting the generated content like this:
if ($section == 'summary_main')
{
$summary_page_content['content'] =
$summary_page_content['details'] .
$items_content .
$summary_page_content['messaging_received'] .
$summary_page_content['footer']
;
$template->set('members_area_page_content', $summary_page_content['content']);
}
Everything works except for the content generated by $items_content , which only displays 1 item no matter if there are 1 or 20. I tried to do a
$items_content . =
instead of
$items_content =
but that didn't seem to work either and just gave me an error.
What am I doing wrong?
It's not $db->fetch_array($sql_select_items) it's $sql_selected_items->fetch_array(). Here's how I would do it:
$table_rows = $db->query("SELECT * FROM table WHERE ...");
if($table_rows->num_rows > 0){
$table = '<table><tbody>';
while($row = $table_rows->fetch_object()){
$table .= "<tr><th>{$row->title_column_name}</th><td>{$row->other_column_name}</td></tr>";
}
$table .= '</tbody></table>';
}
else{
$table = '';
// no results
}
echo $table;
$table_rows->free(); $db->close();
Outside of (before) the while loop:
$items_content = '';
Inside the while loop:
$items_content .= '...';
This will make sure that your $items_content variable exists before your loop, and then the .= will concatenate your string to the end of $items_content.
"What am I doing wrong?"
As you didn't post the error, I can only assume you either got an undefined variable notice, which is solved by placing $items_content = ''; before the loop, or your got a syntax error because the operator you should be using is .= and not . = (note that the space is wrong).
I am using another company's API to retrieve information from their database, it is being returned to me in XML format. I'm trying to accomplish two things - but am having a couple issues.
1st I would like to format the raw XML data into a table format, that will be easier to view via browser.
2nd The data I am receiving is IDs/usernames/passwords/emails. I would like to be able to import that data into my DB so that each userID is a row inserted into the DB (I can do the DB work, I just can't figure out how to process each user individually )
The API formatting is like this <API> <message> <user> <id> </id> <login> </login> <password> </password> <message> </message> </API> only there will be hundreds of user's instead of just one.
Whenever I just do a print of $array, I get the data as a big blob as intended. However, when I use the updated code, (below) I receive an error that user is not a valid index. I also receive what looks to be the start of my table, without any data in it (only borders).
If anyone could help me figure out why the table is not receiving data (or give me advice on a better way to do it) I would greatly appreciate it.
Extra points for anyone who can help me figure out number two.
Error is Notice: Undefined index: user in /home/public_html/new/test.php on line 36 line 36 is commented in the code
Here is the bottom part of my code:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Method execution
$result = curl_exec($ch);
// Close CURL session
$array = json_decode(json_encode((array)simplexml_load_string($result)),1);
$array_user=$array['user']; //line 36
$tab='<table border="1" width="400">';
for ($j=1; $j< count($array_user) ; $j++) {
$tab.='<tr>';
$tab.='<td>'.$array_user[$j]['id'].'</td>';
$tab.='<td>'.$array_user[$j]['login'].'</td>';
$tab.='<td>'.$array_user[$j]['mail'].'</td>';
$tab.='<td>'.$array_user[$j]['date'].'</td>';
$tab.='</tr>';
}
$tab.='</table>';
echo $tab;
?>
$sxe = simplexml_load_string('<API><message><user><id>10</id><login>a</login><password>abc</password></user><user><id>11</id><login>456</login><password>def</password></user></message></API>');
// or $sxe = simplexml_load_file($xml_url);
function tabulate(SimpleXMLElement $sxe) {
if (!count($sxe)) return '';
$table = "<table border='1' width='400'>\n";
$header = false;
foreach($sxe as $row) {
if (!$header) {
$table .= "<thead>\n<tr>\n\t";
foreach ($row as $field) {
$table .= "<th>";
$table .= htmlspecialchars($field->getName(), ENT_NOQUOTES, 'UTF-8');
$table .= "</th>";
}
$table .= "\n</tr>\n</thead>\n<tbody>\n";
$header = true;
}
$table .= "<tr>\n\t";
foreach ($row as $field) {
$table .= "<td>";
$table .= htmlspecialchars((string) $field, ENT_NOQUOTES, 'UTF-8');
$table .= "</td>";
}
$table .= "\n</tr>\n";
}
$table .= "</tbody>\n</table>";
return $table;
}
function insert_users(PDO $db, SimpleXMLElement $users) {
$ins = $db->prepare('INSERT INTO users (id, login, password) VALUES (?,?,?)');
foreach ($users as $user) {
$userdata = array((string) $user->id, (string) $user->login, (string) $user->password);
$ins->execute($userdata);
}
}
insert_users($db, $sxe->message->user);
echo tabulate($sxe->message->user);
SimpleXMLElement cheat sheet
This is how you loop through your XML using simplexml.
You can build a table or a query from this.
$xml = simplexml_load_string($x); // XML is in $x
foreach ($xml->user as $user) {
echo $user->id . ': ' . $user->login . ' : '
echo $user->password . ' : ' . $user->message . '<br />;
}
see it working: http://codepad.viper-7.com/KhWsla
BTW: your xml needs repair:
<API>
<user>
<id>1</id>
<login>michi</login>
<password>12345</password>
<message>hi!</message>
</user>
</API>
I'm a newbie at GA API so I have no clue how to extract results the correct way in this case.
e.g. I'm trying to extract avgTimeOnPage values based on filtering from ga:pagePath = ...
But each one is returning a single digit value on ga:pagePath.. so I'm thinking the ga:pagePath and ga:avgTimeOnPage results are not being displayed correctly. Maybe I'm not extracting the right way.
Anyone who can help would be greatly appreciated.
$ids = 'ga:123456789';
// $start_date $end_date already defined
$filter = 'ga:pagePath==/folder/somepage.html';
$metrics = 'ga:avgTimeOnPage';
$optParams = array('dimensions' => 'ga:pagePath', 'filters' => $filter);
$data = $service->data_ga->
get($ids, $start_date, $end_date, $metrics, $optParams);
foreach($data['totalsForAllResults'] as $rows) :
echo $rows['ga:pagePath']; // why returning a single digit value?
echo $rows['ga:avgTimeOnPage']; // also returns a single digit
endforeach;
$data['totalsForAllResults'] will return a single row that is the total row. You are looking for the values not the totals. so you should use:
foreach ($data->getRows() as $row) :
And then you can iterate $rows for every cell.
Check this full example:
private printDataTable(&$results) {
if (count($results->getRows()) > 0) {
$table .= '<table>';
// Print headers.
$table .= '<tr>';
foreach ($results->getColumnHeaders() as $header) {
$table .= '<th>' . $header->name . '</th>';
}
$table .= '</tr>';
// Print table rows.
foreach ($results->getRows() as $row) {
$table .= '<tr>';
foreach ($row as $cell) {
$table .= '<td>'
. htmlspecialchars($cell, ENT_NOQUOTES)
. '</td>';
}
$table .= '</tr>';
}
$table .= '</table>';
} else {
$table .= '<p>No Results Found.</p>';
}
print $table;
}
source: https://developers.google.com/analytics/devguides/reporting/core/v3/coreDevguide#working