开发者

can't assign value to variable inside recursive function

开发者 https://www.devze.com 2023-03-16 00:20 出处:网络
I\'m trying to create a XML file dynamically trough php, reading DIRS and FILES on a specific directory on my ftp.

I'm trying to create a XML file dynamically trough php, reading DIRS and FILES on a specific directory on my ftp.

So far so god, here's the code:

<?php

$path = ".";


$dir_handle = @opendir($path) or die("Unable to open $path");

function list_dir($dir_handle,$path)
{



    while (false !== ($file = readdir($dir_handle))) {

        $dir =$path.'/'.$file;
    $link =$path.'/';


        if(is_dir($dir) && $file != '.' && $file !='..' )

        {

        $handle = @opendir($dir) or die("unable to open file $file");

    $xmlString .= '<' . $file . '>';

    list_dir($handle, $dir);

    $xmlString .= '</' . $file . '>';


        }

    elseif($file != '.' && $file !='..' && $file !='ftpteste.php')

        {

    $xmlString .= '<IMAGE>';
    $xmlString .= '&开发者_StackOverflow社区lt;PHOTO>' . $link . '' . $file . '</PHOTO>';
    $xmlString .= '</IMAGE>';

        }
    }


closedir($dir_handle);

}



$xmlString ='<XML>';

list_dir($dir_handle,$path);

$xmlString .="</XML>";





$strXMLhead = '<?xml version="1.0" encoding="UTF-8" ?>';
$xmlString = $strXMLhead . "\n" . $xmlString;



$xmlLoc = "../../interiores/xml/content.xml";

$fileXML = fopen($xmlLoc, "w+") or die("Can't open XML file");


if(!fwrite($fileXML, pack("CCC",0xef,0xbb,0xbf)))
{
print "Error Saving File";
}
else
{
fwrite($fileXML, $xmlString);
print "XML file saved";
}

fclose($fileXML);

?>

The problem is that i'm getting no output on $XmlString running inside the function. If i use Print instead joining the strings it's fine, it does the job. But i need it to be in a variable in order to save to file.

Saving to file it's ok.

It should output something like:

<XML>

<$DIR NAME>
<IMAGE>
<PHOTO>$FILE_NAME</PHOTO>
</IMAGE>
</$DIR NAME>

</XML>

Can anyone help me with this?

thanks in advance, artur


I think you should take a look at the DomDocument object. It provides an easy way to create a document with nodes (like an xml document). You will be able to avoid your problem with that.


Return the XML you're building from list_dir().

function list_dir($dir_handle,$path)
{
    ...
    $xmlString .= list_dir($handle, $dir);
    ...
    return $xmlString;
}

$xmlString = '<XML>' . list_dir($dir_handle,$path) . '</XML>';
0

精彩评论

暂无评论...
验证码 换一张
取 消