Some people have mentioned to me that my site is quite inefficient and given that it's taking ~17secs to load now, I'd like to change that but I've no idea how. I've tried Gzip to compress it but it didn't help. I got rid of some double quotes (I.e. "") and have used single quotes (I.e. '') instead, as well as got rid of some HTML blank spaces but that's about it.

Here is most of my code, excluding some JS to save space. Either way, when I open the Google Chrome developer console on my site, it shows that it's the PHP file itself that takes so long to load, not JS so that's why I'm just showing that below. It's just this one page that's loading slowly, all others sites are very quick. I'd love some tips on how to make this more efficient.

        // Page name
    $title = 'Portfolio';
    // Include the header template

    // If for some reason, not logged in then redirect to login page
    if(!$user->is_logged_in()){ header('Location: login.php'); exit(); }
    <h2><?php echo htmlspecialchars($_SESSION['username'], ENT_QUOTES); ?></h2>
    <button id="opener" class='btn btn-success' >Advanced Company Data</button>
    <div id="dialog" title="Advanced Company Data"><a href="http://www.nasdaq.com/symbol/aapl">Exchange Information</a>
            autoOpen: false
        $("#opener").click(function() {
            $("#dialog").dialog("open", "modal", true );
    $spy = file_get_contents('https://api.iextrading.com/1.0/stock/spy/stats/year1ChangePercent');  
    $spy = json_decode($spy,TRUE); 
    // Initialising variables to store extracted information
    $name = [];
    $symbol = [];
    $open = [];
    $close = [];
    $high = [];
    $low = [];
    $lastprice = [];
    $y = 0;
    $z = '';
    $key = '93dcc722279c3a7577f248b09ef6167f';

    // Retreiving information from database
    $memberid = $_SESSION['memberID'];
    $sql = "SELECT * FROM portfolio WHERE memberID = $memberid";
    $result = mysqli_query($conn, $sql);

    // Check if databse is empty
    if (mysqli_num_rows($result) > 0) 
        while($row = mysqli_fetch_assoc($result)) 
            $sym[$y] = $row['stocks_symbol'];
            $pri[$y] = $row['price'];
            $vol[$y] = $row['quantity'];
            $id[$y] = $row['memberid'];
            $y += 1;
    // If database empty
        echo 'Portfolio Empty';

    // Adding all stock names in one variable to enable API call
        $z = $z.$sym[$a].',';
    $z = rtrim($z,',');

    // API call
    $contents = file_get_contents("http://marketdata.websol.barchart.com/getQuote.json?key=$key&symbols=$z&mode=R");
    $contents = json_decode($contents, true);
    // Check successfull API call
    if($contents['status']['code'] == 200) 
        foreach($contents['results'] as $result) 
    // If API call unsuccessful
        echo 'Error retreiving data. Please try again later.';
<!-- Generating Output in tabular format -->
<table id= test class='table table-responsive'>
    <tr class='head warning'>
        <th>Last Price</th>
        <th>Price Bought</th>
        <th>Change Per Stock</th>
        <th>Amount Invested</th>
        <th>Current Market Value</th>
        <th>Total Dividend</th>
        <th>Company Description</th>
        <th>Latest News</th>
    $profitOrLossSum = 0;
    $dividendRateSum = 0;
    $startEqSum = 0;
    $sumOf = array();
    $pnl = array();

                <td class="input"><?php echo $name[$x]; ?></td>
                <td class="input"><?php echo $symbol[$x]; ?></td>
                <td class="input"><?php echo $open[$x]; ?></td>
                <td class="input"><?php echo $close[$x]; ?></td>
                <td class="input"><?php echo $high[$x]; ?></td>
                <td class="input"><?php echo $low[$x]; ?></td>
                <td class="input"><?php echo $lastprice[$x]; ?></td>
                <td class="input"><?php echo $pri[$x]; ?></td>
                <td class="input"><?php echo $vol[$x]; ?></td>
                <td class="input"><?php 
                    if($pri[$x] > $lastprice[$x]) 
                        echo $lastprice[$x]-$pri[$x];
                    else if($pri[$x] < $lastprice[$x]) 
                        echo $lastprice[$x]-$pri[$x];
                        echo '0';
                <td class="input"><b><?php 
                    $profitOrLoss = ($lastprice[$x]-$pri[$x]) * $vol[$x];
                    $profitOrLossSum += $profitOrLoss;
                    $pnl[] = $profitOrLoss;
                    echo $profitOrLoss;
                    $starteq = $pri[$x] * $vol[$x];
                    $startEqSum += $starteq;
                    echo $starteq;
                    $firstno1  = floatval($vol[$x]);
                    $secondno1 = floatval($lastprice[$x]);
                    $sumOf[] = $firstno1 * $secondno1;
                    $sum1 = $firstno1 * $secondno1;
                    echo ($sum1);
                    $div = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=stats&filter=dividendRate");  
                    $div = json_decode($div,TRUE);  
                    $sum = 0;
                    foreach($div as $divi => $value) {
                    echo $value['stats']['dividendRate']; 
                    $sum += (floatval($vol[$x]) + floatval($value['stats']['dividendRate']));
                    $firstno  = floatval($vol[$x]);
                    $secondno = floatval($value['stats']['dividendRate']);
                    $sum2 = 0;
                    $sum2 += $firstno * $secondno;
                    echo ($sum2);
                    $dividendRateSum += $sum2;
                <td class="input"><?php
                        $desc = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=company&filter=description");  
                        $desc = json_decode($desc,TRUE); 
                        foreach($desc as $desc => $des) {
                        echo $des['company']['description'];
                    $desc1 = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=news&filter=headline,url&range=1m&last=1");  
                    $desc1 = json_decode($desc1,TRUE); 
                    foreach($desc1 as $key111 => $des1) {
                    echo implode(PHP_EOL, array_column($des1['news'],'headline'));
                    ?><br><?php $link = implode(PHP_EOL, array_column($des1['news'],'url'));
                    echo '<a href="'.$link.'">Link</a>';
    $arr = array('profitOrLossSum' => $profitOrLossSum, 'dividendRateSum' => $dividendRateSum);
    $arr1 = array('startEqSum' => $startEqSum);     
    $array = array_combine($name, $sumOf);
    $array10 = array_combine($name, $pnl);

<h3> SPY %YTD= <?php echo $spy1 = number_format($spy *100, 2); ?>%</h3>
        <h3> Starting Equity= $<?php echo $startEqSum; ?></h3>
        <h3> Current Equity= $<?php echo $profitOrLossSum; ?></h3>
        <h3> Total Profit= $<?php echo $profitOrLossSum - $startEqSum; ?></h3>
        <h3> % Gain/Loss= <?php echo $gain = number_format((($profitOrLossSum - $startEqSum) / $startEqSum) * 100, 2); ?>%</h3>
        <h3> Total Dividend= $<?php echo $dividendRateSum / 4; ?>/Quarter</h3>
        <h3> Portfolio vs SPY= <?php echo $gain-$spy1; ?>%</h3><br>

You should copy your page and write the time taken for all file-get-content and for the query. So you ll know where come that it s very slow. How many people are using it? How many people are using your server? If too many it s saturated and very very slow : change your server or the internet connection or optimise your code. Next use echo to write text it s faster than stoping the script and coming back. Better to redo a sql query instead of downloading a file. You could also cache the most used queries eventually in a new database table. If using the script tag you should always inform what is the language. If you use only once a session variable, it s faster not to save it first in a variable. If you just need to display a value only don t save it in an array first but at the moment of running the query. Prefer to use variable instead of array it s faster.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.