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