0

I am using simple_html_dom to parse a page and return some content.

When I try to output the content with print_r in the foreach loop, it returns all elements. However, if I try to output the contents to a text file, it only outputs the last element. What am I doing wrong?

Here is my sample code:

include 'simple_html_dom.php';

$partlist_file = $_SERVER['DOCUMENT_ROOT'].'/partlist.txt';

$partlist = file('knn-partnumberlist.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

$stock = '';

    $output_first = '';
    foreach($partlist as $parts => $part) {

        $html = file_get_html('search/product.aspx?prod=' . $part);
        $ret = $html->find('span#cph_lb_stock_buy'); 

        foreach($ret as $element) {
            $stock = $element->plaintext;
            $stock = preg_replace(array('/\\n/','/\\r/'),'',$stock);
            $stock = trim($stock);
            if($stock == 'Not in stock.') {
                $stock = '0';
            } elseif($stock == 'In Stock & Ready to Ship!') {
                $stock = '6';
            }



        $output = 'K33' . $part . ',' . $stock . "\n";
        print_r ($output); // returns all elements
        file_put_contents($partlist_file, $output); // only returns last element

        }
    }

Sample of print_r output:

K3300283,6
K3301518,6
K3301988,6
K3303351,6
K3303365,6

Sample of file_put_contents output:

K3303365,6
Mike
  • 607
  • 8
  • 30

2 Answers2

1

You need to concatenate $output for each iteration,without it is simply overwritten

 $output .= 'K33' . $part . ',' . $stock . "\n";
        print_r ($output);
        file_put_contents($partlist_file, $output);

. is the concatenation operator

Mihai
  • 26,325
  • 7
  • 66
  • 81
  • thanks, that is what I was using. But with print_r on screen it produces something different. It works good for the file_put_contents though. Why does it give different results for print_r? – Mike Jul 30 '15 at 06:10
  • @Mike print_r is called for each iteration of the loop so you see it on the screen while in $output is is overwritten for each iteration so you only get the last value. – Mihai Jul 30 '15 at 06:12
  • ok, what would I need to do in order to see it on screen with print_r the same as it outputs to the text file? – Mike Jul 30 '15 at 06:17
  • 1
    Also move the print_r and file_put_contents calls outside of the loop you are rewriting the file 5 times. – Orangepill Jul 30 '15 at 06:18
  • @Orangepill oh yeah, thanks for catching that for me. – Mike Jul 30 '15 at 06:19
  • 1
    What is happening in your code is that each time through the loop it is writing a single element to the output buffer and creating a file with one line in it. Each time through the array the output buffer gets appended to but the file gets overwritten. – Orangepill Jul 30 '15 at 06:21
0

The print_r function has a boolean option that allows it to be returned as a string variable, rather than print it to the screen. It's usage is something like:

$myVar = print_r($otherVar, true);

This will allow you to collect the value, rather than printing it directly to the output buffer (e.g. screen). This would prove useful in that you can now manipulate the value as needed or desired.

Additionally, file_put_contents also has an option that allows you to append to the file, rather than overwrite it's current contents. Again, usage would look like this:

$dummy = file_put_contents('path/to/file', $varToSave, FILE_APPEND);

That last option is an integer bit flag (I don't know it's actual value) that tells PHP to add the new data to the end of the file instead of replacing the current contents with the new data. The use of both of these options would look like this in your original code:

include 'simple_html_dom.php';

$partlist_file = $_SERVER['DOCUMENT_ROOT'].'/partlist.txt';

$partlist = file('knn-partnumberlist.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

$stock = '';

$output_first = '';
foreach($partlist as $parts => $part) {

    $html = file_get_html('search/product.aspx?prod=' . $part);
    $ret = $html->find('span#cph_lb_stock_buy'); 

    foreach($ret as $element) {
        $stock = $element->plaintext;
        $stock = preg_replace(array('/\\n/','/\\r/'),'',$stock);
        $stock = trim($stock);
        if($stock == 'Not in stock.') {
            $stock = '0';
        } elseif($stock == 'In Stock & Ready to Ship!') {
            $stock = '6';
        }



    $output = 'K33' . $part . ',' . $stock . "\n";
    $display = print_r ($output, true);
    // you can manipulate $display here, like so:
    $display = str_replace("\n", "\r\n", $display);
    echo $display; // returns all elements (one at a time)
    file_put_contents($partlist_file, $display, FILE_APPEND); // now stores all values of $output in the file

    }
}

Of course, it looks like you don't really need to manipulate the value of $output in your script, but in order to illustrate the usefulness of the option in print_r, I put in a line of code that replaces Linux newlines (\n) with Windows newlines (\r\n), so that programs like Notepad can properly display the text (PHP's print_r function only places \n newlines in the output, even on Windows machines, which is why I found this post. I was trying to find a way to correct that behavior). That may not prove useful to you at this time, but it may, later, and may prove useful to others who come across this question. I hope this helps. :)

Dave Morton
  • 671
  • 6
  • 16