I am writing a PHP script that uses Twitters API's to get a response of tweets in JSON. I am then using the id's in this JSON as parameters in Twitter's widgets.createTweet() function.
The official twitter documentation for this can be found here.
I believe the problem is at the point where I am trying to icnlude the Twitter widgets.js file within my PHP script.
Here is my entire PHP script with my keys and tokens redacted:
<?php
echo "<h2>Simple Twitter API Test</h2>";
require_once('TwitterAPIExchange.php');
$settings = array(
'oauth_access_token' => ""
'oauth_access_token_secret' => ""
'consumer_key' => ""
'consumer_secret' => ""
)
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$requestMethod = "GET";
if (isset($_GET['user'])) {$user = preg_replace("/[^A-Za-z0-9_]/", '', $_GET['user']);} else {$user = "iagdotme";}
$getfield = "?screen_name=$user&count=$count";
$twitter = new TwitterAPIExchange($settings);
$string = json_decode($twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(),$assoc = TRUE);
if(array_key_exists("errors", $string)) {echo "<h3>Sorry, there was a problem.</h3><p>Twitter returned the following error message:</p><p><em>".$string[errors][0]["message"]."</em></p>";exit();}
$number_tweets = count($string['statuses']);
// THIS IS THE PROBLEM AREA ///////////
echo "<script sync src='https://platform.twitter.com/widgets.js'></script>"
echo "<div class='cols'>";
foreach ($tweet_array['statuses'] as $tweet ) {
$id = $tweet["id"];
echo "<div class='grid-item'><div id='container-$id'></div></div>";
$js_array[] = "twttr.widgets.createTweet('$id', document.getElementById('container-$id'));";
}
echo "</div>";
echo '<script>';
$t = 1;
foreach ($js_array as $js) {
echo $js;
$t++;
}
echo '</script>';
?>
I believe the problem is where I am trying to include the js file from https://platform.twitter.com/widgets.js
It seems to me like everything else here should work. This php file doesn't give me any errors when I try to open it in a browser. I am stuck.
What I'm tyring to do with this code:
make an API call to Twitter and retrieve a set of tweets
use the id's in those tweets to pass
How am I trying to do it:
Using php I have made a successful API call to Twitter with the assistance of an open sourced php library/api wrapper.
store the JSON response in an array, loop through that array getting the tweet id's (attributes for each tweet within the json)
use those id's as parameters for twitter's createTweet function
What my problem is:
I think the problem is, is that my code doesn't know what I mean when I use the twttr.widgets.createTweet() js function because htts://platform.twitter.com/widgets.js is not included properly.
To reiterate, this is where I am trying to include that file:
echo "<script sync src='https://platform.twitter.com/widgets.js'></script>"
Is that piece included properly? If so, are there other things that pop out as erroneous?
Here is a sample of the JSON response from the twitter API call.
{
"statuses": [
{
"created_at": "Wed May 15 15:13:53 +0000 2019",
"id": 1128679903329542144,
"id_str": "1128679903329542144",
"text": "Araw-gabi nasa isip ka, napapanagip ka kahit sa'n magpunta",
"truncated": false,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": []
},
"metadata": {
"iso_language_code": "tl",
"result_type": "recent"
},
"source": "Twitter for Android",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 1016132854999183360,
"id_str": "1016132854999183360",
"name": "L Y S A💛",
"screen_name": "ilysachn",
"location": "Home📍",
"description": "",
"url": null,
"entities": {
"description": {
"urls": []
}
},
"protected": false,
"followers_count": 97,
"friends_count": 73,
"listed_count": 0,
"created_at": "Mon Jul 09 01:32:06 +0000 2018",
"favourites_count": 624,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 188,
"lang": "en",
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "F5F8FA",
"profile_background_image_url": null,
"profile_background_image_url_https": null,
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/1125769288797675520/3Ez4FP9n_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/1125769288797675520/3Ez4FP9n_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/1016132854999183360/1553425392",
"profile_link_color": "1DA1F2",
"profile_sidebar_border_color": "C0DEED",
"profile_sidebar_fill_color": "DDEEF6",
"profile_text_color": "333333",
"profile_use_background_image": true,
"has_extended_profile": false,
"default_profile": true,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 0,
"favorited": false,
"retweeted": false,
"lang": "tl"
},
If you want to know what syntax errors you have in runtime use phpstorm.
I fix errors and now code looks like this
and your script will connect in php file.
<?php
echo "<h2>Simple Twitter API Test</h2>";
require_once('TwitterAPIExchange.php');
$settings = [
'oauth_access_token' => "",
'oauth_access_token_secret' => "",
'consumer_key' => "",
'consumer_secret' => ""
];
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$requestMethod = "GET";
if (isset($_GET['user'])) {
$user = preg_replace("/[^A-Za-z0-9_]/", '', $_GET['user']);
} else {
$user = "iagdotme";
}
$getfield = "?screen_name=$user&count=$count";
$twitter = new TwitterAPIExchange($settings);
$string = json_decode($twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(),$assoc = TRUE);
if(array_key_exists("errors", $string)) {
echo "<h3>Sorry, there was a problem.</h3><p>Twitter returned the following error message:</p><p><em>".$string["errors"][0]["message"]."</em></p>";exit();
}
$number_tweets = count($string['statuses']);
?>
<script sync src='https://platform.twitter.com/widgets.js'></script>
<?php
echo "<div class='cols'>";
foreach ($tweet_array['statuses'] as $tweet ) {
$id = $tweet["id"];
echo "<div class='grid-item'><div id='container-$id'></div></div>";
$js_array[] = "twttr.widgets.createTweet('$id', document.getElementById('container-$id'));";
}
echo "</div>";
?>
Related
I search for some code, even I found it, but I dunno how to add a new line of the javascript he creates.
The original link is this, I have some problem in code bellow. Because I have change the code "price": "120.00", to "price": "\\using php to call some data",.
This is original code:
{
"product_id": "1",
"store_id": "1",
"price": "120.00",
"sequence": "0",
"id": "1",
"parent_id": "0",
"name": "Store 1",
"email": "store1#store1.com"
}
This is what I wrote:
$result1=mysqli_query($conn, "select * from product");
while ($row1=mysqli_fetch_assoc($result1))
{
$pno1 = $row1["no"];
$sql1 = "SELECT * FROM xx where WHERE product_id = '$pno1') ";
$query1 = mysqli_query($conn , $sql1);
$rowcont1 = mysqli_num_rows($query1);
?>
{
"name": "<?php echo $row1["PACKAGE_NAME"]; ?>",
"id": "<?php echo $row1["PACKAGE_NAME"]; ?>",
"cat": "UNIFI",
<?php
if ($rowcont1 == 0)
{
?>
"vas": "<?php echo "No default vas"; ?>"
<?php
}
else
{
?>
"vas": "<?php
while($rowvas1=mysqli_fetch_assoc($query1))
{
echo "$rowvas1[PACKAGE_NAME]\\n\\n"; //This is the line I want to chage (\\n no function for me)
}
?>"
<?php
}
?>
},
<?php
I have found many question same with me, but even I have tried all of the solutions, my code still didn't work
Try the following instead:
echo "$rowvas1[PACKAGE_NAME]<br>";
Instead of \n just add html line-break <br>.
Edit: If you are using the JS provided in the jsfiddle, be sure to change the following line:
$('#price-store').text(pricestore[$('option:selected', this).index()].price);
to(.text( to .html():
$('#price-store').html(pricestore[$('option:selected', this).index()].price);
I'm new and I work in php. I have a problem, I have this "array" result from php script (this array was extracted with php of a html page):
Array ( [0] => {"autostart": false,"controls": true,"flashplayer": "/jwplayer7/jwplayer.flash.swf","image": "I NEED THIS", ga: {}, "mute": false, "ph": 1, "preload": "none", "primary": "html", "repeat": false, "skin": { "name": "tube" }, "stagevideo": true, "stretching": "uniform", "visualplaylist": true, "width": "100%", "aspectratio": "16:9", "provider": 'http', "startparam": "start", tracks: [{"file":"I WANT THIS","kind":"thumbnails"}], "sources": [{"file":"I NEED THIS","label":"480p"},{"file":"I NEED THIS","label":"720p"},"I WANT THIS"] ,"logo": {"logoBar": "I NEED THIS", "target": "blank","link": ""},"displaydescription": false,"displaytitle": false , "abouttext": "RapTu Player", "aboutlink": "" } )
I only need the values from image:, sources:[{"file";}} but I can't get the values, nothing, I try with javascript:
var str = '<?php echo $jw; ?>';
var json = JSON.parse(str);
var parse = $.parseJSON(file);
$jw is the variable of the array, and I don't have any result, nothing is printed. Could you help me? (Sorry for my english).
Upgrade: I resolved it using:
object = [<?php echo $jw; ?>]
for(f=0;f<object.length;f++){
}
Thanks everybody!
if you want doing that.
Then use
var json = '<?php echo json_encode($jw); ?>';
and in json variable you have json from array
or if you only sources you can use
var json = '<?php echo json_encode($jw[0]["sources"]); ?>';
but only work with first element in array $jw
In php:- encode string in php properly
$json = json_encode('{"autostart": false,"controls": true,"flashplayer": "/jwplayer7/jwplayer.flash.swf","image": "I NEED THIS", ga: {}, "mute": false, "ph": 1, "preload": "none", "primary": "html", "repeat": false, "skin": { "name": "tube" }, "stagevideo": true, "stretching": "uniform", "visualplaylist": true, "width": "100%", "aspectratio": "16:9", "provider": "http", "startparam": "start", tracks: [{"file":"I WANT THIS","kind":"thumbnails"}], "sources": [{"file":"I NEED THIS","label":"480p"},{"file":"I NEED THIS","label":"720p"},"I WANT THIS"] ,"logo": {"logoBar": "I NEED THIS", "target": "blank","link": ""},"displaydescription": false,"displaytitle": false , "abouttext": "RapTu Player", "aboutlink": ""}');
$array1 = array($json);
Pass $array1 to html in script:-
var str = '<?php echo $jw; ?>'; // echo $array1[0] as $jw
var json = JSON.parse(str);
var parse = $.parseJSON(file);
Hey Guys I have a problem. I`m new to Cassandra and DataTables and my task is to send data from our 'Cassandra-Server' to the Table plug-in 'DataTables'.
I was looking for some examples or tutorials but I never found one for Cassandra-NoSQL.
I tried the following and this Error is always occurring:
PHP:
//setting header to json
header('Content-Type: application/json');
include 'connect.php';
$statement = new Cassandra\SimpleStatement("SELECT * FROM table1");
$result = $session->execute($statement);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//now print the data
print json_encode($data);
JS:
$(document).ready(function () {
'use strict';
var table = $('#main').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "php/server-side.php",
"type": "GET"
},
"columns": [
{ "data": "name" },
{ "data": "type1" },
{ "data": "type2" },
{ "data": "type3" },
{ "data": "land" },
{
"data": "id",
"orderable": false
}
],
"order": [[0, 'asc']]
});
});
Error:
*Uncaught TypeError: Cannot read property 'length' of undefined
jquery.dataTables.min.js: 39*
I think DataTables don't know what to do with the information (json/$data).
In this example https://datatables.net/examples/data_sources/server_side.html
sspclass.php is used but it is written in SQL so no use for me =(
Can somebody help me with this specific problem?
Instead of "value": "11413425.62", how can I change the code to get the data from database phpMyAdmin?
Here's my full code..
<script type="text/javascript" src="http://static.fusioncharts.com/code/latest/themes/fusioncharts.theme.fint.js?cacheBust=56"></script>
<script type="text/javascript">
FusionCharts.ready(function(){
var fusioncharts = new FusionCharts({
type: 'angulargauge',
renderAt: 'Profit10%',
width: '350',
height: '250',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Total Profit",
"subcaption": "After add value",
"lowerLimit": "0",
"upperLimit": "10000000",
"showValue": "1",
"valueBelowPivot": "1",
"theme": "fint"
},
"colorRange": {
"color": [{
"minValue": "0",
"maxValue": "50000",
"code": "#e44a00"
}, {
"minValue": "50000",
"maxValue": "75000",
"code": "#f8bd19"
}, {
"minValue": "75000",
"maxValue": "100000",
"code": "#6baa01"
}]
},
"dials": {
"dial": [{
"value": "11413425.62"
}]
}
}
}
);
fusioncharts.render();
});
</script>
and the data had been extracted using this file "dataCountryGrossMargin.php" with this code.
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
//connect to the server
$connect= mysql_connect("127.0.0.1","root","");
//$conn = new mysqli($servername, $username, $password);
if(!$connect)
{
die('Could not connect: '.mysql_error($connect));
}
//connect to the database
mysql_select_db("fyp",$connect);
$result = mysql_query("SELECT Country, COGS FROM `table 3`");
$rows = array();
while($r = mysql_fetch_array($result)) {
$row[0] = $r[0];
$row[1] = $r[1];
array_push($rows,$row);
}
print json_encode($rows, JSON_NUMERIC_CHECK);
mysql_close($connect);
?>
Thank you !
You can use a similar approach to the example offered on the Fusioncharts website:
<?php
/* Include the `fusioncharts.php` file that contains functions to embed the charts. */
include("includes/fusioncharts.php");
/* The following 4 code lines contain the database connection information. Alternatively, you can move these code lines to a separate file and include the file here. You can also modify this code based on your database connection. */
$hostdb = "localhost"; // MySQl host
$userdb = "root"; // MySQL username
$passdb = ""; // MySQL password
$namedb = "fusioncharts_phpsample"; // MySQL database name
// Establish a connection to the database
$dbhandle = new mysqli($hostdb, $userdb, $passdb, $namedb);
/*Render an error message, to avoid abrupt failure, if the database connection parameters are incorrect */
if ($dbhandle->connect_error) {
exit("There was an error with your connection: ".$dbhandle->connect_error);
}
?>
<html>
<head>
<title>FusionCharts XT - Column 2D Chart - Data from a database</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<!-- You need to include the following JS file to render the chart.
When you make your own charts, make sure that the path to this JS file is correct.
Else, you will get JavaScript errors. -->
<script src="fusioncharts/fusioncharts.js"></script>
</head>
<body>
<?php
// Form the SQL query that returns the top 10 most populous countries
$strQuery = "SELECT Name, Population FROM Country ORDER BY Population DESC LIMIT 10";
// Execute the query, or else return the error message.
$result = $dbhandle->query($strQuery) or exit("Error code ({$dbhandle->errno}): {$dbhandle->error}");
// If the query returns a valid response, prepare the JSON string
if ($result) {
// The `$arrData` array holds the chart attributes and data
$arrData = array(
"chart" => array(
"caption" => "Top 10 Most Populous Countries",
"paletteColors" => "#0075c2",
"bgColor" => "#ffffff",
"borderAlpha"=> "20",
"canvasBorderAlpha"=> "0",
"usePlotGradientColor"=> "0",
"plotBorderAlpha"=> "10",
"showXAxisLine"=> "1",
"xAxisLineColor" => "#999999",
"showValues" => "0",
"divlineColor" => "#999999",
"divLineIsDashed" => "1",
"showAlternateHGridColor" => "0"
)
);
$arrData["data"] = array();
// Push the data into the array
while($row = mysqli_fetch_array($result)) {
array_push($arrData["data"], array(
"label" => $row["Name"],
"value" => $row["Population"]
)
);
}
/*JSON Encode the data to retrieve the string containing the JSON representation of the data in the array. */
$jsonEncodedData = json_encode($arrData);
/*Create an object for the column chart using the FusionCharts PHP class constructor. Syntax for the constructor is ` FusionCharts("type of chart", "unique chart id", width of the chart, height of the chart, "div id to render the chart", "data format", "data source")`. Because we are using JSON data to render the chart, the data format will be `json`. The variable `$jsonEncodeData` holds all the JSON data for the chart, and will be passed as the value for the data source parameter of the constructor.*/
$columnChart = new FusionCharts("column2D", "myFirstChart" , 600, 300, "chart-1", "json", $jsonEncodedData);
// Render the chart
$columnChart->render();
// Close the database connection
$dbhandle->close();
}
?>
<div id="chart-1"><!-- Fusion Charts will render here--></div>
</body>
</html>
I cant set json in args to use it in casperjs script.
Im launching first casperjs script, it return object in php file and then i need to use it in another one.
im trying to make it like this:
$command = "$casperjs $script $arg0";
$result = shell_exec($command);
$json_data = json_decode($result, true);
//here im getting some data from json but dont change it
$arg1 = json_encode($json_data); // i ried take $result but have the same result
$command = "$casperjs $script2 $arg1";
$json_data = shell_exec($command);
And here i have error:
SyntaxError: Unable to parse JSON string
$result
{ "url": "bilko.com", "webPages": [ { "url": "bilko.com", "links": [ "/site-map", "/en/", "/biography", "/gallery", "/services", "/contacts", "/gallery/corporative", "/gallery/wedding", "/gallery/birthday", "/gallery/teambuilding" ], "content": "\n\t\n\t\t\n\t\n\t \n \n \n \n \n \n" } ], "menus": { "identifier": ".menu", "items": [ [ { "text": "Биография", "url": "/biography" }, { "text": "Галерея", "url": "/gallery" }, { "text": "Услуги", "url": "/services" }, { "text": "Контакты", "url": "/contacts" } ] ] }, "top": { "content": "/images/topLogo.png", "identifier": "header" }, "footer": { "content": "Профессиональный ведущий\nНиколай Билько\n+7 925 025 33 27\n", "identifier": "footer" }, "socBtns": [ [ "https://vk.com/id23333446", "/images/socBtns/vk.png" ] ], "sitemap": [ "/biography", "/contacts", "/en/", "/gallery", "/gallery/birthday", "/gallery/corporative", "/gallery/teambuilding", "/gallery/wedding", "/services", "/site-map", null ] }
in script2 im trying to make
site = JSON.parse(system.args[4]);
If you want to pass data to casperjs then write it to a file and pass the path to the casperjs script. You can then read the contents of the file:
var fs = require("fs");
var site = JSON.parse(fs.read(system.args[4]));
You can write the JSON string to a temporary file in the php script:
$tmp = tempnam(dirname(__FILE__), "tmp");
file_put_contents($tmp, json_encode($json_data));
$json_data = shell_exec("$casperjs $script2 $tmp");
unlink($tmp);
Possible failures might be:
limit of argument length (something like 120 characters)
you can't have spaces in $arg1
your shell might try to interpret "" inside of the JSON string, so enclose the whole string in '': "$casperjs $script2 '$arg1'"
you also have non-ansi characters there that might break the call depending on the shell