Solved

script to pull figures via php and update in realtime?

Posted on 2009-04-11
11
683 Views
Last Modified: 2012-05-06
I recently found a php script that can pull stock quotes from yahoo finance - it works in such a way that everytime my webpage is refreshed, it pulls the latest quote (for say, Google) from yahoo finance, and displays it on the page.

These figures are updated every few seconds, and I was wondering if it would be possible to combine this php script with say some javascript code so that it will retreive and display these figures in real time (or every second or so it will retrieve the figure again, and update the display)???

Anyone have any ideas if this is possible and if so how to do it?
0
Comment
Question by:davids355
  • 5
  • 3
  • 2
  • +1
11 Comments
 
LVL 6

Expert Comment

by:twocandles
ID: 24121283
Use AJAX to execute the php code. Then, with javascript, update the content of the element that is displaying the yahoo finance.
0
 

Author Comment

by:davids355
ID: 24121307
Not sure how or if I can use AJAX? I am running this setup from a hosted server.

As for the javascript side, need some guidance with the actual code if possible.
0
 

Author Comment

by:davids355
ID: 24121326
for reference, I will attach my current code.

You can see the display here:
http://www.shareworld.co.uk
in the right hand column at the top
Class stocktwo

{

function get_stock_quote($symbol)

	{

	$url = sprintf("http://finance.yahoo.com/d/quotes.csv?s=%s&f=sl1c1" ,$symbol);

	$fp = @fopen($url, "r");

	if($fp == FALSE)

		{

		print "Error, Can\'t Open" . "\"$url\"";

		}

	else

		{

		$array = @fgetcsv($fp , 4096 , ",");

		@fclose($fp);

		$this->name = $array[0];

		$this->last = $array[1];

		$this->change = $array[2];

		}

	}

}

 

$quote = new stock;

$quote->get_stock_quote("GOOG");

$str = $quote->change;

$first = $str{0};
 

if ($first == "-")

	{

	$img = "sdown.gif";

	}

else if	($first == "+")

	{

	$img = "sup.gif";

	}

else

	{

	$img = "noc.gif";

	}
 

print "$quote->last" . "$(<img src=\"/uploads/images/$img\">)";

Open in new window

0
 
LVL 14

Accepted Solution

by:
EMB01 earned 500 total points
ID: 24122186
You can create this from scratch if you like; or you can pay $25 bucks to have this AJAX Stock Quoting script from sentosoft:
http://www.sentosoft.com/ajax-stock-ticker.php

Let me know what you want to do.
0
 
LVL 14

Expert Comment

by:EMB01
ID: 24122209
Here's a tutorial (with attached complete code snippet) on how to create an AJAX Stock Ticker for either the NSE:
http://www.bhavyait.co.in/tutorials/nse_stock_ticker.html

Or, the BSE (Bombay Stock Exchange):
http://www.bhavyait.co.in/tutorials/bse_stock_ticker.html

And, last but not least; here's one using Yahoo Finances data:
http://www.bhavyait.co.in/tutorials/yahoo_stock_ticker.html

I've attached the Yahoo Stock Ticker code as reference.

Thank you.
<html>

<head>

	<title>Yahoo stock dashboard by http://www.bhavyait.co.in</title>

	<script type="text/javascript">

		onload = function()

		{

			init();

		}

	</script>
 

	<script type="text/javascript">

		onunload = function()

		{
 

		}

	</script>

	<script type="text/javascript" src="prototype.js"></script>

	<script type="text/javascript">

		/*

		@description Yahoo dashborad javascript

		@createdBy http://www.bhavyait.co.in

		@createdOn 17-10-2007

		@notes This JS is for displaying Yahoo stock quotes data using ajax

		*/

		var watchList = "3IINFOTECH.NS+ABB.NS+BAJAJAUTO.NS+BHEL.NS+CUMMINSIND.NS";
 

		String.prototype.replaceAll=function(s1, s2) {return this.split(s1).join(s2)};

		var xmlhttp=false;

		try {

			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");

		} catch (e) {

			try {

				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

			} catch (E) {

				xmlhttp = false;

			}

		}
 

		if (!xmlhttp && typeof XMLHttpRequest!='undefined') {

			try {

				xmlhttp = new XMLHttpRequest();

			} catch (e) {

				xmlhttp=false;

			}

		}
 

		if (!xmlhttp && window.createRequest) {

			try {

				xmlhttp = window.createRequest();

			} catch (e) {

				xmlhttp=false;

			}

		}
 

		function init(){

			fetchChartData();

		}
 

		function fetchChartData(){

			setTimeout('sendAjaxRequest()', 30*1000);

		}
 

		function sendAjaxRequest(){

			try {

				xmlhttp.open("GET", "http://download.finance.yahoo.com/d/quotes.csv?s="+ watchList +"&f=sl1d1t1c1ohgv&e=.csv",true);

				 xmlhttp.onreadystatechange=function() {

					if (xmlhttp.readyState==4) {

					 fetchChartDataCallback(xmlhttp);

					}

				 }

				xmlhttp.send(null)

			} catch (e){

				document.getElementById("yahoodashboard").innerHTML = e.message;

			}

		}
 
 

		function fetchChartDataCallback(request){

			var response = request.responseText;

			var response1 = response.replaceAll("\"","");

			var response2 = response1.replaceAll("\n","</tr><tr><td>");

			var response3 = response2.replaceAll(",","</td><td><font size='1'>");
 

			var tableData = "" ;

			tableData = "<table border='1' cellspacing='0' cellpadding='0'>";

			tableData = tableData + "<tr>";

			tableData = tableData + "<td><font size='3'><b>Symbol</b></font></td><td><font size='3'><b>Last</b></font></td><td><font size='3'><b>Date</b></font></td> <td><font size='3'><b>Time</b></font></td><td><font size='3'><b>Change</b></font></td><td><font size='3'><b>Open</b></font></td><td><font size='3'><b>High</b></font></td><td><font size='3'><b>Low</b></font></td><td><font size='3'><b>Volume</b></font></td><td>";

			tableData = tableData + "</tr>";

			tableData = tableData + "<tr><td>" +response3 +"</td></tr>";

			tableData = tableData + "</table>";

			document.getElementById("instruction").innerHTML = "";

			document.getElementById("yahoodashboard").innerHTML = tableData;

			fetchChartData();

	}

	</script>

</head>

<body>

	<div id="googlead" align="center">

		<script type="text/javascript">

			<!--

			google_ad_client = "pub-9864082501190213";

			google_ad_width = 728;

			google_ad_height = 90;

			google_ad_format = "728x90_as";

			google_ad_type = "text_image";

			//2007-09-06: Bhavya IT

			google_ad_channel = "3766394562";

			google_color_border = "FFFFFF";

			google_color_bg = "FFFFFF";

			google_color_link = "0000FF";

			google_color_text = "000000";

			google_color_url = "008000";

			//-->

		</script>

	<script type="text/javascript"

		src="http://pagead2.googlesyndication.com/pagead/show_ads.js">

	</script>

	</div>

	<br>

	<div id="provider" align="center">

		<b>Yahoo dashboard using AJAX code provided by <a href="http://www.bhavyait.co.in">http://www.bhavyait.co.in</a><b>

		<br>

		<b>For tutorial visit <a href="http://www.bhavyait.co.in/resources/tutorials.html">Bhavya IT technology and knowledge sharing initiative.</a></b>

		<br>

		<b>See it in action here <a href="http://www.bhavyait.co.in/resources/yahoodashboard.html">Bhavya IT Yahoo stock dashboard.</a></b>

	</div>

	<br>

	<div id="instruction" align="center">

		<table>

			<tr>

				<td>

				<b>The Yahoo dashboard will appear soon</b>

				<br><br>

				<b><font color="red">This only works in IE</font></b>

				<br><br>

				<i>If it does not appear you need to do following to allow data sources access across domains</i>

				<br>

				<li>Open your <b>IE</b></li>

				<li>Go to <b>Tools -> Internet Options</b></li>

				<li>Select <b>Security</b> tab</li>

				<li>Select <b>Custom Level</b> at the bottom</li>

				<li>Go to <b>Miscellaneous</b> section and check <b>Enable</b> under <b>Access data sources across domains</b></li>

				<li>Latest Yahoo data will start updating after every 30 seconds</li>

				</td>

			</tr>

		</table>

	</div>

	<br>

	<div align="center">

		<table>

			<tr>

				<td>

					<b><u>Yahoo stock dashboard</u></b>

				</td>

			</tr>

		</table>

	</div>

	<br>

	<div id="yahoodashboard" align="center"></div>

</body>

<script type="text/javascript">_popupControl();</script>

</html>

Open in new window

0
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 

Author Comment

by:davids355
ID: 24122285
I think I have bought similar from sentisoft before.

And I dont mind paying for this one, however, I dont just want the data displayed, I want it to update in realtime, similar to those on http://cityindex.co.uk/ and igindex.co.uk (you wont see it untill tuesday I guess as the markets are closed now).

What I mean is, after the page is loaded, the script will keep getting data from yahoo and update each field perminantly whilst the page is being viewed...
0
 
LVL 14

Expert Comment

by:EMB01
ID: 24122300
Yeah, I think that's what the AJAX provides (hence a-synchronous). I would check out the free AJAX script that I attached above because the example from sentosoft doesn't seem to be working...
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 24126879
@davids355: regarding this: "I want it to update in realtime,..."

You can get a nice effect from using AJAX to repeatedly refresh the values on the screen, however you have (at least) two issues you need to consider.

First, you need to be aware whether you are violating Yahoo terms of service by republishing their information.  They may have an "umbrella" or passthru TOS agreement that you have implicitly accepted when you use their site.  Look out for this so you do not get sued.

Second, the data you get for free from Yahoo is not real-time data.  It is on a timed delay.  So if someone came to your site, saw the ticker change and made an investment decision, they would be about 15 minutes too late to be in consonance with the market.   Look out for this so you do not get sued.

If you want real time quotes, there are paid services available, and also this:
http://articles.moneycentral.msn.com/Common/FreeCharting.aspx

Yahoo offers this:
http://billing.finance.yahoo.com/realtime_quotes/signup

Best of luck with it, ~Ray
0
 

Author Comment

by:davids355
ID: 24127293
Thanks for the info Ray.

What exactly is AJAX? Is it a server side lanquage? If so, I guess I would have to check whether my provider has it installed wouldnt I?

Good point about yahoo, I will have to check that. Regarding the 15 minute delay, I am aware of that. I would publish a disclaimer regarding it.

The yahoo real time quote software looks very interesting, may be something I could recommend on my site, however it seems to be a software package and not somthing I could actually publish directly on the site (although I have just emailed yahoo to ask this of them,).

Thanks all for the help so far.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 24127302
AJAX stands for Asynchronous JavaScript And XML.  It's the technology that makes web pages look more like desktop applications - the page is dynamic without reloading - just updating parts of the page.  So it is a hybrid of a client-side and server-side application.

Google and Facebook use this a lot.  Here is the simplest explanation I have ever seen, and unfortunately it is not too simple - there are a lot or moving parts to AJAX.  I think this was written by Rasmus Lerdorf of PHP fame.
I find a lot of this AJAX stuff a bit of a hype.  Lots of people have

been using similar things long before it became "AJAX".  And it really

isn't as complicated as a lot of people make it out to be.  Here is a

simple example from one of my apps.  
 

First the Javascript:
 

function createRequestObject() {

    var ro;

    var browser = navigator.appName;

    if(browser == "Microsoft Internet Explorer"){

        ro = new ActiveXObject("Microsoft.XMLHTTP");

    }else{

        ro = new XMLHttpRequest();

    }

    return ro;

}
 

var http = createRequestObject();
 

function sndReq(action) {

    http.open('get', 'rpc.php?action='+action);

    http.onreadystatechange = handleResponse;

    http.send(null);

}
 

function handleResponse() {

    if(http.readyState == 4){

        var response = http.responseText;

        var update = new Array();
 

        if(response.indexOf('|' != -1)) {

            update = response.split('|');

            document.getElementById(update[0]).innerHTML = update[1];

        }

    }

}
 

This creates a request object along with a send request and handle

response function.  So to actually use it, you could include this js in

your page.  Then to make one of these backend requests you would tie it

to something.  Like an onclick event or a straight href like this:
 

  <a href="javascript:sndReq('foo')">[foo]</a>
 

That means that when someone clicks on that link what actually happens

is that a backend request to rpc.php?action=foo will be sent.
 

In rpc.php you might have something like this:
 

  switch($_REQUEST['action']) {

    case 'foo':

      / do something /

      echo "foo|foo done";

      break;

    ...

  }
 

Now, look at handleResponse.  It parses the "foo|foo done" string and

splits it on the '|' and uses whatever is before the '|' as the dom

element id in your page and the part after as the new innerHTML of that

element.  That means if you have a div tag like this in your page:
 

  <div id="foo">

  </div>
 

Once you click on that link, that will dynamically be changed to:
 

  <div id="foo">

  foo done

  </div>
 

That's all there is to it.  Everything else is just building on top of

this.  Replacing my simple response "id|text" syntax with a richer XML

format and makine the request much more complicated as well.  Before you

blindly install large "AJAX" libraries, have a go at rolling your own

functionality so you know exactly how it works and you only make it as

complicated as you need.  Often you don't need much more than what I

have shown here.
 

Expanding this approach a bit to send multiple parameters in the

request, for example, would be really simple.  Something like:
 

  function sndReqArg(action,arg) {

    http.open('get', 'rpc.php?action='+action+'&arg='+arg);

    http.onreadystatechange = handleResponse;

    http.send(null);

  }
 

And your handleResponse can easily be expanded to do much more

interesting things than just replacing the contents of a div.
 

-Rasmus

Open in new window

0
 

Author Comment

by:davids355
ID: 24128560
EMB01:
You can create this from scratch if you like; or you can pay $25 bucks to have this AJAX Stock Quoting script from sentosoft:
http://www.sentosoft.com/ajax-stock-ticker.php

Let me know what you want to do.

I have just found the files from when I bought this software some time ago.

Your right, it does say it should update automatically. I never managed to get it working, however, tomorrow when the markets open I am going to have another try will then report back..

Thanks all
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now