Highstock - Creating an OHLC graph by csv created using php - php

I'm having some problems with importing the csv in order to get the highstock graph.
I'm using the same code as the ohlc example (which works fine locally) but with another CSV which is created on my localhost by php.
PHP to get the CSV
<?PHP
// Declare the new variable as an array
$arrCSV = array();
// Open the CSV file
if (($handle = fopen("http://ichart.finance.yahoo.com/table.csv?s=AAPL&d=7&e=7&f=2012&g=d&a=8&b=7&c=1984&ignore=.csv", "r")) !==FALSE)
{
// Set the parent array key to 0
$key = 0;
// While there is data available loop through unlimited times (0) using separator (,)
while (($data = fgetcsv($handle, 0, ",")) !==FALSE) {
// Count the total keys in each row
$c = count($data);
//print $c . "<BR>"; // <------ 7 o numero de colunas
//Populate the array
If ($key != 0) {
$arrCSV[$key-1][0] = strtotime($data[0]); //Time
$arrCSV[$key-1][1] = $data[1]; //Open
$arrCSV[$key-1][2] = $data[2]; //High
$arrCSV[$key-1][3] = $data[3]; //Low
$arrCSV[$key-1][4] = $data[6]; //Adj Close
$arrCSV[$key-1][5] = $data[5]; //Volume
}
$key++;
} // end while
$keymax = $key;
// Close the CSV file
fclose($handle);
} // end if
print "?(/* AAPL historical OHLC data from the Google Finance API */<BR>";
echo json_encode($arrCSV,JSON_NUMERIC_CHECK);
print ");";
?>
Code to import and create the graph:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highstock Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$.getJSON('http://localhost/teste03.php', function(data) {
// create the chart
chart = new Highcharts.StockChart({
chart : {
renderTo : 'container'
},
rangeSelector : {
selected : 2
},
title : {
text : 'AAPL Stock Price'
},
series : [{
type : 'ohlc',
name : 'AAPL Stock Price',
data : data,
dataGrouping : {
units : [[
'week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]
]]
}
}]
});
});
});
</script>
</head>
<body>
<script src="js/highstock.js"></script>
<script src="js/modules/exporting.js"></script>
<div id="container" style="height: 500px; min-width: 500px"></div>
</body>
</html>
In the end it just get me a blank page...
Is this caused by being using localhost? The order of the array (descendent instead of ascendent)?
Help?
Update: json_encode added but still doesn't work.

FURTHER EDITED
Seems that you might have ajax issues, try doing an isolated test by
Using the SimpleTest.php (refer OLD section for code) and hosting it on the same server as your current teste03.php, and access the chart from it
$.getJSON('http://localhost/SimpleTest.php', function(data) {
...
}
OR
<script type="text/javascript">
$(function() {
// $.getJSON('http://localhost/teste03.php', function(data) {
var data= [[1000000,1,2,3,4],[2000000,3,2,3,4],[1000000,1,2,3,4]];
// create the chart
chart = new Highcharts.StockChart({
...
If any of the above approaches work, means that you have an ajax issue and not a highcharts issue.
EDITED (based on your comment about the json that was returned)
The timestamp values in the data need to be in ascending order. From your following json
[[1344290400,622.77,625,618.04,618.26,10373100],[1344204000,617.29,624.87,615.26‌​,619.89,10789400]
1344290400>1344204000 hence wont work.
OLD
use the json_encode method for the json formation.
What you need to pass to it is, an array of array where the outer array is of the size same as the number of rows in the CSV, and each element of this outer array is another array with 5 elements, viz. timestamp, open, high, low, close.
SimpleTest.php:
<?php
// JSON header
header('Content-type: application/json');
// Do not cache the response
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
// Parse CSV, and populate the 5 arrays viz. $timeStamp, $open, $high, $low, $close
$count=3;
$timeStamp=array(1000000,2000000,3000000); // In ascending order of time
$open=array(5,10,15);
$high=array(10,15,20);
$low=array(0,5,10);
$close=array(8,12,18);
$dataArray=array(); // Outer array of array
for( $i=0; $i<$count; $i++ ){
// push an array into $dataArray for each data group
$dataArray[] = array($timeStamp[$i], $open[$i], $high[$i], $low[$i],$close[$i]);
}
echo json_encode($dataArray); // Encode php array of array into json and echo/print it to output
?>
Looking at your code, i think you can tweak you $arrCSV to transform into the required array.

Related

How to pass only text part of html code `(excluding the tags)` to php page using get method from ajax

I want to export the mysql data to excel file through ajax
Ajax code
$('#dateBox').change(function(){
$('#getData').html('loading...');
var date = $('#dateBox').val();
var limit = $('#sortByNo').val();
//set download button attributes
$('#exportSilver').attr('data-date',date);
if(date != ''){
var action = 'getDataFromDate';
$.ajax({
url: 'fetch_payouts.php',
method: 'post',
data: {date:date,action:action,limit:limit},
success:function(data){
$('#getData').html(data);
window.location.href = 'download.php?data='+data+'';
}
});
}
else{
$('#getData').html('');
}
});
download.php file
<?php
if(isset($_GET['data'])){
$data = $_GET['data'];
// The function header by sending raw excel
header("Content-type: application/vnd-ms-excel");
// Defines the name of the export file "codelution-export.xls"
header("Content-Disposition: attachment; filename=insway.xls");
echo $data;
}
?>
It works but the problem is it also exports the html tags to the excel file and there are two rows in the database table and it only exports one row and two columns from second row
This is the excel file output
You can strip all the tags from the array $_GET['data']
try following code:
$data = array_map(function($v){
return trim(strip_tags($v));
}, $_GET['data']);
Or simply
$data = array_map( 'strip_tags', $_GET['data'] );
You can use strip_tags function of PHP on data before echoing it.
Maybe like this:
$data = array_map(trim(strip_tags($data))
So the new code looks like:
<?php
if(isset($_GET['data'])){
$data = $_GET['data'];
// The function header by sending raw excel
header("Content-type: application/vnd-ms-excel");
// Defines the name of the export file "codelution-export.xls"
header("Content-Disposition: attachment; filename=insway.xls");
$data = array_map(trim(strip_tags($data));
echo $data;
}
?>

PHP Best practice to display all lines from file containing enormus number of lines

I have one file 1.2MB and in it, there are 36k+ lines of text and probably growing. The problem is that I want to display all the lines from input.txt but since there are too many lines I get out with a browser crash...What I have tried so far is:
<?php
$handle = fopen("input.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo '<li class="list-group-item d-flex justify-content-between align-items-center">'.$line.'</li>';
}
fclose($handle);
} else {
echo 'error';
}
?>
This code works for files that are about 40KB approx 1400lines anything more will result in a crash...
After that I thought if I load that file to db and then conn with php and get data from base I will be able to display all lines, but again I was wrong
<?php
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ime_pjesme FROM pjesme";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<li class="list-group-item d-flex justify-content-between align-items-center">'. $row["ime_pjesme"].'</li>';
}
} else {
echo "0 results";
}
$conn->close();
?>
So my question is is there any way/method I could use to get those lines displayed in browser or is there way to load it and then display 50 by 50 etc?
Yes, there is a way to display the file a page at a time.
There are many libraries that will do it nicely for you, but to understand the mechanisms, here's how to do it with just the jQuery library and some PHP.
Simply put, you need two files. The first will display the page counter/selector and the area where the rows will appear. Say that you want 50 rows at a time:
$pages = floor(($rownumber + 50 - 1)/ 50);
print "<ul class=\"pageselect\">";
for ($i = 0; $i < $pages; $i++) {
$p = $i + 1;
print "<li data-page=\"{$p}\">Page {$p}</li>";
}
print "</ul>";
You organize the CSS so that the LI elements are all nice, centered and horizontal. Then you use e.g. jQuery to attach an event handler to the clicking on one of those LI's by delegating to the parent UL, in Javascript:
$('ul.pageselect').on('click', 'li', function() {
var wanted = $(this).attr('data-page');
$.post('/path/to/page_load.php', { page: wanted })
.then(reply => {
// "reply" is the object returned by the loader PHP.
$('#lines').empty();
for (var l = 0; l < reply.lines.length; l++) {
$('#lines').append($('<p>').text(reply.lines[l]));
}
});
});
The delegate function issues an AJAX POST call to the second PHP file, and expect a JSON reply (called reply here) to be processed.
The above will kill the contents of a DIV such as <div id="lines"></div> and fill it with as many P's as there are lines in the loader reply.
The loader receives a parameter which is the page number, translates it to an absolute line number, runs the select and returns everything in JSON format:
$from = (((int)$_POST['page'])-1) * 50;
if ($from < 0) { $from = 0; }
// Run a SELECT with OFFSET {$from},50 to fetch at most 50 rows
$reply = [
'total' => $total, // use SQL_CALC_FOUND_ROWS to get the total number
'lines' => [ ]
];
while ($rs->fetch(PDO::PDO_FETCH_ASSOC) as $line) {
$reply['lines'] = "This line is {$line['text']}.";
}
header('Content-Type: application/json; charset=UTF8');
// Return JSON encoding of $reply to the caller.
exit(json_encode($reply));
You will find the browser tools invaluable to inspect what's going on with the AJAX calls. The "loader" file you will be able to recycle later with most of the niftier libraries.

Codeigniter view show progress

I am using Codeigniter and want to show progress of XML import.
but issue i am facing is
When view load, it stuck on loading (blank page) and when i can see view its shows 100% done.
my code as bellow
$i=0;
$count=sizeof($record->List);
foreach($record->List as $Item)
{
$i++;
echo "processing ".$i." of ".$count;
---processing code which takes times to process---
---processing code which takes times to process---
}
this code is in view but when i click on link to load this view, i have to wait for all process to complete and then i can see view when all process is done.
what i want is:
Show view (empty).
Then keep on printing each line as loop go.
Thanks
Here you got a example for progress bar using AJAX:
index.php
<?php
// Start the session.
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Progress Bar</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<style>
#progress {
width: 500px;
border: 1px solid #aaa;
height: 20px;
}
#progress .bar {
background-color: #ccc;
height: 20px;
}
</style>
</head>
<body>
<div id="progress"></div>
<div id="message"></div>
<script>
var timer;
// The function to refresh the progress bar.
function refreshProgress() {
// We use Ajax again to check the progress by calling the checker script.
// Also pass the session id to read the file because the file which storing the progress is placed in a file per session.
// If the call was success, display the progress bar.
$.ajax({
url: "checker.php?file=<?php echo session_id() ?>",
success:function(data){
$("#progress").html('<div class="bar" style="width:' + data.percent + '%"></div>');
$("#message").html(data.message);
// If the process is completed, we should stop the checking process.
if (data.percent == 100) {
window.clearInterval(timer);
timer = window.setInterval(completed, 1000);
}
}
});
}
function completed() {
$("#message").html("Completed");
window.clearInterval(timer);
}
// When the document is ready
$(document).ready(function(){
// Trigger the process in web server.
$.ajax({url: "process.php"});
// Refresh the progress bar every 1 second.
timer = window.setInterval(refreshProgress, 1000);
});
</script>
</body>
</html>
checker.php
<?php
// The file has JSON type.
header('Content-Type: application/json');
// Prepare the file name from the query string.
// Don't use session_start here. Otherwise this file will be only executed after the process.php execution is done.
$file = str_replace(".", "", $_GET['file']);
$file = "tmp/" . $file . ".txt";
// Make sure the file is exist.
if (file_exists($file)) {
// Get the content and echo it.
$text = file_get_contents($file);
echo $text;
// Convert to JSON to read the status.
$obj = json_decode($text);
// If the process is finished, delete the file.
if ($obj->percent == 100) {
unlink($file);
}
} else {
echo json_encode(array("percent" => null, "message" => null));
}
process.php
<?php
// Start the session.
session_start();
// The example total processes.
$total = 20;
// The array for storing the progress.
$arr_content = array();
// Loop through process
for ($i = 1; $i <= $total; $i++) {
// Calculate the percentation
$percent = intval($i / $total * 100);
// Put the progress percentage and message to array.
$arr_content['percent'] = $percent;
$arr_content['message'] = $i . " row(s) processed.";
// Write the progress into file and serialize the PHP array into JSON format.
// The file name is the session id.
file_put_contents("tmp/" . session_id() . ".txt", json_encode($arr_content));
// Sleep one second so we can see the delay
sleep(1);
}
Just that you write it on the CI and create a tmp folder, and you point a path to it in script. Good luck!

Tags of html not working in php

Hi i have a small line of code where i got data from mysql database and tried to display that data using html tag.I am able to display the chart but The real problem is if i write the html tag, to display the data inside the chart then tags are not working and even tags areg getting printed in side the chart with my data
If i use echo to write html code, then i am getting this kind of error.
[![enter image description here][1]][1]
Error : syntax error, unexpected 'echo' (T_ECHO).
Please go through the code , i dont know where i had done the mistake.
foreach ($results as $row) {
$temp = array();
$temp[] = array('v' => $row['Email'],'f' => "<p>{$row['First_Name']}</p><p>{$row['Email']}</p><img src = {$row['imageurl']} width='100px' height='100px'></img>");
$temp[] = array('v' => $row['Name'],'f' => "{$row['Name'] }{$row['Name']}");
$table['rows'][] = array('c' => $temp);
}
$jsonTable = json_encode($table);
<script type="text/javascript">
function drawVisualization() {
var jtable = <?php echo $jsonTable; ?>
// Create and populate the data table.
var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
// Create and draw the visualization.
var table = new google.visualization.OrgChart(document.getElementById('visualization'));
table.draw(data, {allowHtml:true});
}
google.setOnLoadCallback(drawVisualization);
google.load('visualization', '1', {packages: ['orgchart']});
google.visualization.events.trigger(table,'select', function() {
alert('selected');
});
// Add our over/out handlers.
</script>
\
i had added table.draw(data, {allowHtml:true});
I made a mistake by not writing allowHtml, because of this reason my html tags were not working
Thanks,
Sai Nishank

An Ajax request is taking 6 seconds to complete, not sure why

I am working on a user interface, "dashboard" of sorts which has some div boxes on it, which contain information relevant to the current logged in user. Their calendar, a todo list, and some statistics dynamically pulled from a google spreadsheet.
I found here:
http://code.google.com/apis/spreadsheets/data/3.0/reference.html#CellFeed
that specific cells can be requested from the sheet with a url like this:
spreadsheets.google.com/feeds/cells/0AnhvV5acDaAvdDRvVmk1bi02WmJBeUtBak5xMmFTNEE/1/public/basic/R3C2
I briefly looked into Zend GData, but it seemed way more complex that what I was trying to do.
So instead I wrote two php functions: (in hours.php)
1.) does a file_get_contents() of the generated url, based on the parameters row, column, and sheet
2.) uses the first in a loop to find which column number is associated with the given name.
So basically I do an ajax request using jQuery that looks like this:
// begin js function
function ajaxStats(fullname)
{
$.ajax({
url: "lib/dashboard.stats.php?name="+fullname,
cache: false,
success: function(html){
document.getElementById("stats").innerHTML = html;
}
});
}
// end js function
// begin file hours.php
<?php
function getCol($name)
{
$r=1;
$c=2;
while(getCell($r,$c,1) != $name)
{ $c++; }
return $c;
}
function getCell($r, $c, $sheet)
{
$baseurl = "http://spreadsheets.google.com/feeds/cells/";
$spreadsheet = "0AnhvV5acDaAvdDRvVmk1bi02WmJBeUtBak5xMmFTNEE/";
$sheetID = $sheet . "/";
$vis = "public/";
$proj = "basic/";
$cell = "R".$r."C".$c;
$url = $baseurl . $spreadsheet . $sheetID . $vis . $proj . $cell . "";
$xml = file_get_contents($url);
//Sometimes the data is not xml formatted,
//so lets try to remove the url
$urlLen = strlen($url);
$xmlWOurl = substr($xml, $urlLen);
//then find the Z (in the datestamp, assuming its always there)
$posZ = strrpos($xmlWOurl, "Z");
//then substr from z2end
$data = substr($xmlWOurl, $posZ + 1);
//if the result has more than ten characters then something went wrong
//And most likely it is xml formatted
if(strlen($data) > 10)
{
//Asuming we have xml
$datapos = strrpos($xml,"<content type='text'>");
$datapos += 21;
$datawj = substr($xml, $datapos);
$endcont = strpos($datawj,"</content>");
return substr($datawj, 0,$endcont);
}
else
return $data;
}
?>
//End hours.php
//Begin dashboard.stats.php
<?php
session_start();
// This file is requested using ajax from the main dashboard because it takes so long to load,
// as to not slow down the usage of the rest of the page.
if (!empty($_GET['name']))
{
include "hours.php";
// GetCollumn of which C#R1 = users name
$col = getCol($_GET['name']);
// then get cell from each of the sheets for that user,
// assuming they are in the same column of each sheet
$s1 = getcell(3, $col, 1);
$s2 = getcell(3, $col, 2);
$s3 = getcell(3, $col, 3);
$s4 = getcell(3, $col, 4);
// Store my loot in the session varibles,
// so next time I want this, I don't need to fetch it
$_SESSION['fhrs'] = $s1;
$_SESSION['fdol'] = $s2;
$_SESSION['chrs'] = $s3;
$_SESSION['bhrs'] = $s4;
}
//print_r($_SESSION);
?>
<!-- and finally output the information formated for the widget-->
<strong>You have:</strong><br/>
<ul style="padding-left: 10px;">
<li> <strong><?php echo $_SESSION['fhrs']; ?></strong> fundraising hours<br/></li>
<li>earned $<strong><?php echo $_SESSION['fdol']; ?></strong> fundraising<br/></li>
<li> <strong><?php echo $_SESSION['chrs']; ?></strong> community service hours<br/></li>
<li> <strong><?php echo $_SESSION['bhrs']; ?></strong> build hours <br/></li>
</ul>
//end dashboard.stats.php
I think that where I am loosing my 4 secs is the while loop in getCol() [hours.php]
How can I improve this, and reduce my loading time?
Should I just scrap this, and go to Zend GData?
If it is that while loop, should i try to store each users column number from the spreadsheet in the user database that also authenticates login?
I didn't have the proper break in the while loop, it continued looping even after it found the right person.
Plus the request take time to go to the google spreadsheet. About .025 second per request.
I also spoke with a user of ZendGdata and they said that the request weren't much faster.

Categories