Search code examples
phparraysxpathfputcsv

PHP + XPath + fputcsv - Storing data in arrays


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);

Solution

  • 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);
    
        ?>