I'm trying to use an ESP8266 NodeMCU to retrieve data from a database on my web page to control a LED. I'm struggling with the code on both sides for the ESP8266 to ask for the data and the web page to return it. I have the web page and database built. Here is the relevant bit of the server side PHP file, which isn't working....
if(!empty($_GET['mode']) && !empty($_GET['brightness']))
{
$mode = $_GET['mode'];
$brightness = $_GET['brightness'];
$sql = "SELECT * FROM config ORDER BY id DESC LIMIT 1 (mode, brightness)
$result = $conn->query($sql);
SELECT fields FROM table ORDER BY id DESC LIMIT 1;
VALUES ('".$mode."', '".$brightness."')";
if ($conn->query($sql) === TRUE) {
echo "1" . $row["id"]."<br>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
<code>
and on the ESP8266 side....
getData = "?mode=" "&brightness=";
Link = "http://***.com/Feed.php" + getData;
http.begin(Link); //Specify request destination
int httpCode = http.GET();
String payload = http.getString();
Mode = payload.substring(0,3);
String Brightness = payload.substring (4,6);
Thanks in advance!
I changed my approach and got it working. Instead of trying to return data from the web page to the ESP8266 I displayed the data on a very simple page....
<?php
$con=mysqli_connect("localhost","*****","*****","*****");
if (mysqli_connect_errno()) { echo "Failed to connect to config: " . mysqli_connect_error(); }
$result = mysqli_query($con,"SELECT * FROM config ORDER BY id DESC LIMIT 1");
while ($row = $result->fetch_assoc()) {
$mode = $row[mode]; $brightness = $row[brightness]; $speed = $row[speed];
print $mode;
print $brightness;
print $speed;
}
?>
and then had the ESP download the entire page and parsed out the data using substring like so...
HTTPClient http; //Declare object of class HTTPClient
Link = "http://*****.com/*****.php";
http.begin(Link); //Specify request destination
int httpCode = http.GET(); //Send the request
String payload = http.getString(); //Get the response payload
Mode = payload.substring(156,158).toInt();
Speed = payload.substring(158,160).toInt();
Brightness = payload.substring(160,162).toInt();
Related
I am looking for a way to ignore first row which is the header row when inserting data into mysql database using PhpOffice\PhpSpreadsheet.I have followed this but not workingSkip First Row in PHPSpreadsheet ImportMy problem is how to ignore the header row?
Below is my clean code...
use Phppot\DataSource;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
require_once ('./vendor/autoload.php');
if (isset($_POST["import"])) {
$allowedFileType = [
'application/vnd.ms-excel',
'text/xls',
'text/xlsx',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
];
if (in_array($_FILES["file"]["type"], $allowedFileType)) {
$date = date('Y-m-d');
$targetPath = 'uploads/'.$date." ".$_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $targetPath);
$Reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
if($Reader) {
$Reader->setReadDataOnly(true);
$spreadSheet = $Reader->load($targetPath);
$sheetData = $spreadSheet->getActiveSheet()->toArray();
// Loop through the rows from xlsx file for insert
foreach($sheetData as $row) {
// get columns in a contigeous order from xlsx file
$regno = isset($row[0]) ? $row[0] : "";
$fullname = isset($row[1]) ? $row[1] : "";
$course = isset($row[2]) ? $row[2] : "";
$status = 1;
$pin = strtoupper(substr(md5(mt_rand()), 0, 10));
// Insert into db
$fieUploaded = $conn->itStudentsFileUpload($regno,$fullname,$course,$pin,$current_session,$status);
// If all is well send success message
if ($fieUploaded) {
echo "Success";
}
}
}
} else {
$type = "error";
$message = "Invalid File Type. Upload Excel File.";
}
}
After several tests, I solve the problem as follows:
class FirstRowFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter
{
public function readCell($column, $row, $worksheetName = '') {
// Return true for rows after first row
return $row > 1;
}
}
$Reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader("Xlsx");
$filterRow = new FirstRowFilter();
$Reader->setReadFilter($filterRow);
$spreadSheet = $Reader->load($targetPath);
$sheetData = $spreadSheet->getActiveSheet()->toArray();
Note:
If you have additional fields that are not from the excel file eg. date, you need to check for emptiness of the first row from the excel file and then insert if not empty to ignore inserting empty values.
We tried to code Google Translate in action script for Flash Professional CS6, but it does not function .
Can anyone help ?
The code does not return the trasnlated result .
The Code :
private function translate(e)
{
var result_lv:LoadVars = new LoadVars();
result_lv.onLoad = function () {
var str:String = unescape(this);
var txtContent;
var translatedText:String = str.split('":"')[1].split('"}, ')[0];
if(translatedText != undefined)
txtContent.text = translatedText.split('r').join('n').split('"').join("'");
return txtContent.text;
}
var lorem_lv:LoadVars = new LoadVars();
var from:String = "fa";
var to:String = "en"
lorem_lv.v = "1.0";
lorem_lv.format = "text";
lorem_lv.q = e;
lorem_lv.langpair = from + "|" + to;
lorem_lv.sendAndLoad(" http://ajax.googleapis.com/ajax/services/language/translate ", result_lv, "GET");
}
Code Explained :
Sample
LoadVars.sendAndLoad( )
Method Code Explained :
https://flylib.com/books/en/4.13.1.377/1/
================================================
Edit 1:
I edited my code :
I added the return code to the main function , so the main function has output .
but still the function does not return any transalted content .
The improved code :
private function translate(e)
{
var result_lv:LoadVars = new LoadVars();
var txtContent;
result_lv.onLoad = function () {
var str:String = unescape(this);
var translatedText:String = str.split('":"')[1].split('"}, ')[0];
if(translatedText != undefined)
txtContent.text = translatedText.split('r').join('n').split('"').join("'");
return txtContent.text;
}
var lorem_lv:LoadVars = new LoadVars();
var from:String = "fa";
var to:String = "en"
lorem_lv.v = "1.0";
lorem_lv.format = "text";
lorem_lv.q = e;
lorem_lv.langpair = from + "|" + to;
lorem_lv.sendAndLoad(" http://ajax.googleapis.com/ajax/services/language/translate ", result_lv, "GET");
return txtContent.text;
}
================================================
Edit 2:
We have found a working PHP function that return the translated result properly :
https://github.com/statickidz/php-google-translate-free/blob/1.1.1/src/GoogleTranslate.php
Now we are trying to load the PHP function result in the Action Script 2 for Adobe Flash Professional CS6.
here is some explanation about how this is possible :
Flash calling a PHP function
================================================
Edit 3:
A Good and Complete Book about PHP for Flash :
Foundation PHP for Flash 1st Edition :
https://www.amazon.com/Foundation-PHP-Flash-Steve-Webster/dp/1903450160
================================================
Edit 4:
Some Other Good and Complete Books about PHP for Flash :
Foundation PHP 5 for Flash 1st Edition :
https://www.amazon.com/Foundation-PHP-Flash-David-Powers/dp/B0096EPX7Q
Advanced PHP for Flash 1st ed. Edition :
https://www.amazon.com/Advanced-PHP-Flash-Steve-Webster/dp/1590591879
================================================
Edit 5:
We have rewritten the action script function that now use the PHP GoogleTranslate function .
See the answers below .
But it does not return the Translated result .
Please can someone help ?
Thanks
In the PHP-script that you've mentioned in comments, authors used the link https://translate.google.com/translate_a/single?... with some client authenticaton data like iid and also set User-Agent to Android phone:
curl_setopt($ch, CURLOPT_USERAGENT, 'AndroidTranslate/5.3.0.RC02.130475354-53000263 5.1 phone TRANSLATE_OPM5_TEST_1');
I think this script is trying to masquerade request like it was sent from Android Google Translate App.
But in your AcrionScript code you are using another URL:
lorem_lv.sendAndLoad(" http://ajax.googleapis.com/ajax/services/language/translate ", result_lv, "GET");
This simple-HTTP Google Translate API v1 is very old and already not available.
You can check it yourself by following this link - it's responds 404.
Here is the code that we have written :
Our function is written using the sample code on the below address :
Easy way to bring a php variable on flash with AS2
but it does not return the translated result . when I set the return String value to e variable the function work . but when I set the return to $output variable it does not function .
Action Script 2 Code :
function googletranslate(e:String):String
{
/*LoadVars send example*/
// init LoadVars Object
var lv:LoadVars = new LoadVars();
// set Variables
lv.sVar1 = "fa";
lv.sVar2 = "en";
lv.sVar3 = e;
// define onLoad Callback
lv.onLoad = onLoadCallBack;
// send and load variables
lv.sendAndLoad("google-translate-result.php?", lv, "POST");
var $output;
// onLoad Callback
function onLoadCallBack(succes)
{
// if succes
if(succes)
{
// trace variables
$output = this.lVarresult;
}
else
{
// loading failed
$output = "Loading Error!!";
}
}
return $output;
}
=============================================================
Edit :
The PHP (google-translate-result.php) Code is changed :
$_POST changed to $_GET and now the result php code is working itself through using this url :
Server_URL/google-translate-result.php?sVar1=fa&sVar2=en&sVar3=%DA%A9%D8%AA%D8%A7%D8%A8%20%D8%AA%D8%B3%D8%AA
but still the ActionScript does not return the Translated Result .
=============================================================
PHP Code (google-translate-result.php) :
<?php
require_once('GoogleTranslate.php');
// get variables
$var1 = $_GET['sVar1'];
$var2 = $_GET['sVar2'];
$var3 = $_GET['sVar3'];
$result = GoogleTranslate::translate($var1,$var2,$var3);
// send variables
echo "&lVarresult=$result&";
PHP Code (GoogleTranslate.php) :
<?php
/**
* GoogleTranslate.class.php
*
* Class to talk with Google Translator for free.
*
* #package PHP Google Translate Free;
* #category Translation
* #author Adrián Barrio Andrés
* #author Paris N. Baltazar Salguero <sieg.sb#gmail.com>
* #copyright 2016 Adrián Barrio Andrés
* #license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* #version 2.0
* #link https://statickidz.com/
*/
/**
* Main class GoogleTranslate
*
* #package GoogleTranslate
*
*/
class GoogleTranslate
{
/**
* Retrieves the translation of a text
*
* #param string $source
* Original language of the text on notation xx. For example: es, en, it, fr...
* #param string $target
* Language to which you want to translate the text in format xx. For example: es, en, it, fr...
* #param string $text
* Text that you want to translate
*
* #return string a simple string with the translation of the text in the target language
*/
public static function translate($source, $target, $text)
{
// Request translation
$response = self::requestTranslation($source, $target, $text);
// Get translation text
// $response = self::getStringBetween("onmouseout=\"this.style.backgroundColor='#fff'\">", "</span></div>", strval($response));
// Clean translation
$translation = self::getSentencesFromJSON($response);
return $translation;
}
/**
* Internal function to make the request to the translator service
*
* #internal
*
* #param string $source
* Original language taken from the 'translate' function
* #param string $target
* Target language taken from the ' translate' function
* #param string $text
* Text to translate taken from the 'translate' function
*
* #return object[] The response of the translation service in JSON format
*/
protected static function requestTranslation($source, $target, $text)
{
// Google translate URL
$url = "https://translate.google.com/translate_a/single?client=at&dt=t&dt=ld&dt=qca&dt=rm&dt=bd&dj=1&hl=es-ES&ie=UTF-8&oe=UTF-8&inputm=2&otf=2&iid=1dd3b944-fa62-4b55-b330-74909a99969e";
$fields = array(
'sl' => urlencode($source),
'tl' => urlencode($target),
'q' => urlencode($text)
);
// URL-ify the data for the POST
$fields_string = "";
foreach ($fields as $key => $value) {
$fields_string .= $key . '=' . $value . '&';
}
rtrim($fields_string, '&');
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_USERAGENT, 'AndroidTranslate/5.3.0.RC02.130475354-53000263 5.1 phone TRANSLATE_OPM5_TEST_1');
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
return $result;
}
/**
* Dump of the JSON's response in an array
*
* #param string $json
* The JSON object returned by the request function
*
* #return string A single string with the translation
*/
protected static function getSentencesFromJSON($json)
{
$sentencesArray = json_decode($json, true);
$sentences = "";
foreach ($sentencesArray["sentences"] as $s) {
$sentences .= isset($s["trans"]) ? $s["trans"] : '';
}
return $sentences;
}
}
According to the Comments of the previous answer Action Script 2 Code changed to:
function googletranslate(e:String):String
{
/*LoadVars send example*/
// init LoadVars Object
var lv:LoadVars = new LoadVars();
var result_lv:LoadVars = new LoadVars();
// set Variables
lv.sVar1 = "fa";
lv.sVar2 = "en";
lv.sVar3 = e;
// send and load variables
lv.sendAndLoad("google-translate-result.php?", result_lv, "POST");
return result_lv.lVarresult;
}
Im looking for a function that will pull the youtube duration of a video from the url. I read some tutorials but don't get it. I embed videos on my site using a url and I have a function that pulls the thumbnail and I just want something similar that gets the duration. Here's how I get the thumb...
function get_youtube_screen_link( $url = '', $type = 'default', $echo = true ) {
if( empty( $url ) )
return false;
if( !isset( $type ) )
$type = '';
$url = esc_url( $url );
preg_match("|[\\?&]v=([^&#]*)|",$url,$vid_id);
if( !isset( $vid_id[1] ) )
return false;
$img_server_num = 'i'. rand(1,4);
switch( $type ) {
case 'large':
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/0.jpg";
break;
case 'first':
// Thumbnail of the first frame
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/1.jpg";
break;
case 'small':
// Thumbnail of a later frame(i'm not sure how they determine this)
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/2.jpg";
break;
case 'default':
case '':
default:
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/default.jpg";
break;
}
if( $echo )
echo $img_link;
else
return $img_link;
}
You could use something like this:
<?php
function getDuration($url){
parse_str(parse_url($url,PHP_URL_QUERY),$arr);
$video_id=$arr['v'];
$data=#file_get_contents('http://gdata.youtube.com/feeds/api/videos/'.$video_id.'?v=2&alt=jsonc');
if (false===$data) return false;
$obj=json_decode($data);
return $obj->data->duration;
}
echo getDuration('http://www.youtube.com/watch?v=rFQc7VRJowk');
?>
that returns the duration in seconds of the video.
Reference: http://code.google.com/apis/youtube/2.0/developers_guide_protocol.html
You can use a function like this one to change the seconds to hours, minutes, and seconds.
youtube api v3
usage
echo youtubeVideoDuration('video_url', 'your_api_key');
// output: 63 (seconds)
function
/**
* Return video duration in seconds.
*
* #param $video_url
* #param $api_key
* #return integer|null
*/
function youtubeVideoDuration($video_url, $api_key) {
// video id from url
parse_str(parse_url($video_url, PHP_URL_QUERY), $get_parameters);
$video_id = $get_parameters['v'];
// video json data
$json_result = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$video_id&key=$api_key");
$result = json_decode($json_result, true);
// video duration data
if (!count($result['items'])) {
return null;
}
$duration_encoded = $result['items'][0]['contentDetails']['duration'];
// duration
$interval = new DateInterval($duration_encoded);
$seconds = $interval->days * 86400 + $interval->h * 3600 + $interval->i * 60 + $interval->s;
return $seconds;
}
This is my function to get youtube duration in second.
he is fully 100% work.
you need just youtube id video and youtube api key.
how to add youtube api key show
this video https://www.youtube.com/watch?v=4AQ9UamPN6E
public static function getYoutubeDuration($id)
{
$Youtube_KEY='';
$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id={$id}&key={$Youtube_KEY}");
$vTime='';
$H=0;
$M=0;
$S=0;
$duration = json_decode($dur, true);
foreach ($duration['items'] as $vidTime) {
$vTime = $vidTime['contentDetails']['duration'];
}
$vTime = substr($vTime, 2);
$exp = explode("H",$vTime);
//if explode executed
if( $exp[0] != $vTime )
{
$H = $exp[0];
$vTime = $exp[1];
}
$exp = explode("M",$vTime);
if( $exp[0] != $vTime )
{
$M = $exp[0];
$vTime = $exp[1];
}
$exp = explode("S",$vTime);
$S = $exp[0];
$H = ($H*3600);
$M = ($M*60);
$S = ($H+$M+$S);
return $S;
}
This is my function to get youtube duration in second.
he is fully 100% work.
you need just youtube id video and youtube api key.
how to add youtube api key show
this video https://www.youtube.com/watch?v=4AQ9UamPN6E
You can simply use a time formater to change the seconds into whatever format you like.
i.e. return gmdate("H:i:s", $obj->data->duration);
function getYoutubeDuration($videoid) {
$xml = simplexml_load_file('https://gdata.youtube.com/feeds/api/videos/' . $videoid . '?v=2');
$result = $xml->xpath('//yt:duration[#seconds]');
$total_seconds = (int) $result[0]->attributes()->seconds;
return $total_seconds;
}
//now call this pretty function.
//As parameter I gave a video id to my function and bam!
echo getYoutubeDuration("y5nKxHn4yVA");
1) You will need an API key. Go to https://developers.google.com/ and log in or create an account, if necessary. After logging in go to this link https://console.developers.google.com/project and click on the blue CREATE PROJECT button. Wait a moment as Google prepares your project.
2) You will need a web host that is running PHP with file_get_content supported. You can check by creating a new script with just "echo php_info();" and verifying that allow_url_fopen is set to On. If it is not, then change the configuration or talk to your web host.
<?php
$sYouTubeApiKey = "<enter the key you get>";
//Replace This With The Video ID. You can get it from the URL.
//ie https://www.youtube.com/XWuUdJo9ubM would be
$sVideoId = "XWuUdJo9ubM";
//Get The Video Details From The API.
function getVideoDetails ($sVideoId) {
global $sYouTubeApiKey;
//Generate The API URL
$sUrl = "https://www.googleapis.com/youtube/v3/videos?id=".$sVideoId."&key=".$sYouTubeApiKey."&part=contentDetails";
//Perform The Request
$sData = file_get_contents($sUrl);
//Decode The JSON Response
return json_decode($sData);
}
//Get The Video Duration In Seconds.
function getVideoDuration ($sVideoId) {
$oData = getVideoDetails($sVideoId);
//Deal With No Videos In List
if (count($oData->items) < 1) return false;
//Get The First Video
$oVideo = array_shift($oData->items);
//Extract The Duration
$sDuration = $oVideo->contentDetails->duration;
//Use Regular Expression To Parse The Length
$pFields = "'PT(?:([0-9]+)H)?(?:([0-9]+)M)?(?:([0-9]+)S)?'si";
if (preg_match($pFields, $sDuration, $aMatch)) {
//Add Up Hours, Minutes, and Seconds
return $aMatch[1]*3600 + $aMatch[2]*60 + $aMatch[3];
}
}
header("Content-Type: text/plain");
$oData = getVideoDetails($sVideoId);
print_r($oData);
echo "Length: ".getVideoDuration($sVideoId);
?>
Hope this helps!
I am trying to retrieve data from database through php scripts and display in flash using actionscript 3.
For actionscript 3, I have 2 functions:
private var postArrayTxt:Array;
public function stampTwo() {
// constructor code
var stampNumber1:MovieClip = new stamp1();
var stampNumber2:MovieClip = new stamp2();
var stampNumber3:MovieClip = new stamp3();
postArrayTxt = new Array();
postArrayTxt[0] = stampNumber1;
postArrayTxt[1] = stampNumber2;
postArrayTxt[2] = stampNumber3;
trace("All stamps works");
retrieveDetailsFromDB();
}
The data retrieved from database will be displayed in the various movieclips where it will be calling retrieveDetailsFromDB().
public function retrieveDetailsFromDB():void {
var myLoader:URLLoader = new URLLoader();
myLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
myLoader.load(new URLRequest("http://localhost/Converse/stampGalore/tryout.php"));
myLoader.addEventListener(Event.COMPLETE, onDataLoad);
// Error Handling
myLoader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
myLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
// Could be an error or just a message
myLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus);
function onDataLoad(evt:Event): void {
//var loader:Loader = new Loader();
//stamp221.addChild(loader);
//loader.load(new URLRequest(evt.target.data.facebookRemarks));
var delimiter:String = "|^_^|";
var stamp:String = evt.target.data.databaseRemarks;
trace(stamp);
var stampRemarkArr:Array = new Array();
stampRemarkArr = stamp.split(delimiter);
for (var i:Number=0; i<stampRemarkArr.length; i++) {
postArrayTxt[i].text = String(stampRemarkArr[i]);
trace("ended");
}
}
// error callbacks
function onIOError(evt:IOErrorEvent) {
trace("IOError: " + evt.text);
}
function onHTTPStatus(evt:HTTPStatusEvent) {
trace("HTTPStatus: " + evt.status);
}
function onSecurityError(evt:SecurityErrorEvent) {
trace("SecurityError: " + evt.text);
}
}
Last but not least, this is my php script.
<?php
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
include_once "mysqli.connect.php";
$sql = "SELECT remarks FROM stamp";
$result = $mysqli->query($sql);
if ($mysqli->errno)
{
error_log($mysqli->error);
return;
}
$facebook = "";
$counter = 0;
while ($row = $result->fetch_array())
{
$database = $row["remarks"];
$delimiter = "|^_^|";
if ($counter == 0) {
$facebook .=$database;
} else {
//Use a delimiter "|^_^|" to seperate the records
$facebook .= $delimiter . $database;
}
$counter++;
}
$mysqli->close();
echo "databaseRemarks=" . $facebook;
?>
if I were to run the php script itself, the data could be retrieved from database. However, if I run in Flash, it returns a null value. Please help me as I have wasted a lot of time on this retrieve function. Thank you
This won't work:
var stamp:String = evt.target.data.databaseRemarks;
Flash doesn't know in which format is your data so you need to parse it first. So first read the data:
var rawData:String = evt.currentTarget.data;
Then parse it:
var parsedData:* = someFunctionToParseYourData(rawData);
I am using tmhOAuth.php / class to login into twitter. I have been successful in logging in and sending a tweet.
When I go to use the friends.php script, I am having some problems inserting into my database. I do believe that my problem lies some where with the $paging variable in the code. Because it is looping only seven times. I am following 626 people so my $ids is 626 and then $paging is 7.
When I run the php in a web browser, I am only able to extract 7 of the followers (ie following user #626,following user 526,following user 426...) It seem to be echoing the last user on each page request. This due in part to requesting 100 user ids at a time, via the PAGESIZE constant. When I adjust the $paging with different number such as the number 626 I get {"errors":[{"code":17,"message":"No user matches for specified terms"}]}
Unfortunately, I suspect this is fairly simple php looping problem, but after the amount of time I have spent trying to crack this I can no longer think straight.
Thanks in advance.
define('PAGESIZE', 100);
require 'tmhOAuth.php';
require 'tmhUtilities.php';
if ($tmhOAuth->response['code'] == 200) {
$data = json_decode($tmhOAuth->response['response'], true);
$ids += $data['ids'];
$cursor = $data['next_cursor_str'];
} else {
echo $tmhOAuth->response['response'];
break;
}
endwhile;
// lookup users
$paging = ceil(count($ids) / PAGESIZE);
$users = array();
for ($i=0; $i < $paging ; $i++) {
$set = array_slice($ids, $i*PAGESIZE, PAGESIZE);
$tmhOAuth->request('GET', $tmhOAuth->url('1/users/lookup'), array(
'user_id' => implode(',', $set)
));
// check the rate limit
check_rate_limit($tmhOAuth->response);
if ($tmhOAuth->response['code'] == 200) {
$data = json_decode($tmhOAuth->response['response'], true);
if ($tmhOAuth->response['code'] == 200) {
$data = json_decode($tmhOAuth->response['response'], true);
$name = array();
foreach ($data as $val)
{
$name = $data[0]['screen_name'];
}
echo "this is the screen name " .$name. "\n";
$users += $data;
} else {
echo $tmhOAuth->response['response'];
break;
}
}
var_dump($users);
?>
The data I am trying to echo, then parse and insert into database is the standard twitter JSON data, so I won't include this in the message. Any help would be
Problem solved:
foreach ($data as $val)
{
$name = $val['screen_name'];
echo "this is the screen name " .$name. "\n";
$users[] = $name;
}