0

I'm parsing some HTML with DOM/Xpath, with the ultimate goal of generating a .CSV file with the data I've grabbed with my queries.

The current code below works, but only returns the last product name. I know I'm sort of on the right track here, but I'm maxed out and cannot figure this out. Any help would be greatly, greatly appreciated. Thanks.

$names = array();
$result = $xpath->query("//div[@class='product-name']");
foreach ($result as $nam) {
$names[] = $nam->nodeValue;
$i = 0;
$values=$names[$i] = $nam->nodeValue;
}

$list = array (
    array('Product Name','Stock Level','Price'),
    array($values, '456', '789'),
);

$fp = fopen('product-sheet.csv', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);
rocky
  • 464
  • 6
  • 22

2 Answers2

1

The problem is you're setting $i inside your loop.

foreach ($result as $nam) {
$names[] = $nam->nodeValue;
$i = 0;
$values=$names[$i] = $nam->nodeValue;
}

On each iteration, $i is being reset to 0. Try something like this instead:

for($i=0; $i< count($result); $i++) {
    $names[] = $result->nodeValue;
    $values=$names[$i] = $result->nodeValue;
}
IsisCode
  • 2,490
  • 18
  • 20
  • I'm not sure what you're trying to do sorry. Could you describe your aim in detail please? Specifically with regards to those arrays; how do you want them to be structured? – IsisCode May 02 '12 at 20:00
1

I'm not entirely sure what you're trying to achieve but hopefully this will get you nearer to your goal.

<?php

        //mocked up input, substitute for your HTML source
        $input = "<html>
                    <div class='product-name'>test1</div>
                    <div class='product-name'>test2</div>
                    <div class='product-name'>test3</div>
                    <div class='product-name'>test4</div>
                    <div class='product-name'>test5</div>
                </html>";

        $doc = new DOMDocument();
        @$doc->loadHTML($input);
        libxml_use_internal_errors(FALSE);
        $xpath = new DomXPath($doc);

        $list = array (
            array('Product Name','Stock Level','Price')
        );

        $result = $xpath->query("//div[@class='product-name']");

        foreach ($result as $nam) {
            $value = $nam->nodeValue;
            $list[] = array($value, '456', '789');  //Appends an array to the lists array
        }

        $fp = fopen('product-sheet.csv', 'w');

        foreach ($list as $fields) {
            fputcsv($fp, $fields);
        }

        fclose($fp);

    ?>
IsisCode
  • 2,490
  • 18
  • 20