简体   繁体   中英

Beginner help need for simple PHP script

I'm a complete beginner in php (and a first 'poster' here on SO) and seem to be missing something in a small script that I am doing from a tutorial.

What the script is basically suppose to do is get Ticker names from a hosted txt file on the server and output historical prices fetched from yahoo finance.

Everything seems to be working fine except that the content that i get from the getCSVfile function is incorrect (I get the html from the yahoo error page). The fetched URL is however correct and if I type in the targeted URL manually everything works just fine.

It is probably a basic mistake but can't seem to find it. Seems to be related to '' and ""s.

Many thanks in advance for the help Y

<?php 

include("includes/connect.php");

function createURL($ticker){
    $currentMonth = date('n') - 1;
    $currentDay = date('j');
    $currentYear = date('Y');
    $result = 'http://ichart.finance.yahoo.com/table.csv? s='.$ticker.'&a=07&b=19&c=2012&d=11&e=08&f=2012 &g=d&ignore=.csv';
    return (string)$result;
}

function getCSVFile($url, $outputFile){
    $content = file_get_contents($url);
    $content = str_replace('Date,Open,High,Low,Close,Volume,Adj Close','',$content);
    $content = trim($content);
   echo $content; /debugging
  file_put_contents($outputFile,$content);
}

//test debugging - this is where the problem seems to be happening - 
//the URL output is correct as is the getCSVfile but the combination of the two doesnt  work properly//

$test = createURL('GOOG');
echo $test;
getCSVFile($test, "memory.txt");

/code continues...

?>

The problem is that your URL does contain a few spaces which do not belong in there:

$result = 'http://ichart.finance.yahoo.com/table.csv? s='.$ticker.'&a=07&b=19&c=2012&d=11&e=08&f=2012 &g=d&ignore=.csv';
                                                     ^                                               ^

Try

$result = 'http://ichart.finance.yahoo.com/table.csv?s='.$ticker.'&a=07&b=19&c=2012&d=11&e=08&f=2012&g=d&ignore=.csv';

instead.

To notice this kind of error, it is always the best way to copy'n'paste your debug output in the browser, not type it in -- otherwise you will often miss these small, obvious errors.

Try using urlencode before returning the URL in your createURL function. So the code of that function would be something like this

function createURL($ticker){
$currentMonth = date('n') - 1;
$currentDay = date('j');
$currentYear = date('Y');
$result = 'http://ichart.finance.yahoo.com/table.csv? s='.$ticker.'&a=07&b=19&c=2012&d=11&e=08&f=2012 &g=d&ignore=.csv';
return urlencode($result);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM