Search code examples
phpfpdf

Write array as unordered list to PDF


I have a recursive function creating an unordered list from an array. I now want that list in a PDF using FPDF. How should I modify this function to write the PDF? I have tried the following, but no results in the produced PDF. I think this is to do with the way FPDF needs to have Cell contents written through concatenation.

$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',12);

$pdf_result = '';

function walk($array)
{    
    //convert object to key-value array
    if (is_object($array)) {
        $array = (array)$array;
    }
    $pdf_result .= "<ul>";
    foreach ($array as $key => $value) {
        if (is_int($value) || is_string($value)) {
            $pdf_result .=  "<li>" . $value;            
        } elseif (is_array($value) || is_object($value)) {
            walk($value);
        }
        $pdf_result .=  "</li>";
    }
    $pdf_result .=  "</ul>";
}

walk($roots);

$pdf->Cell(40,10,$pdf_result);
$pdf->Output('MD by Year');

Solution

  • Your $pdf_result is not global variable. So it must be like this:

    function walk($array)
    {    
        //convert object to key-value array
        if (is_object($array)) {
            $array = (array)$array;
        }
    
        $pdf_result = "<ul>";
        foreach ($array as $key => $value) {
            if (is_int($value) || is_string($value)) {
                $pdf_result .=  "<li>" . $value;            
            } elseif (is_array($value) || is_object($value)) {
                $pdf_result .= walk($value);
            }
            $pdf_result .=  "</li>";
        }
        $pdf_result .=  "</ul>";
    
        // Here we return result array
        return $pdf_result;
    }
    
    // And here we set another-scope variable from function
    $pdf_result = walk($roots);