简体   繁体   中英

json_encode returning null from php array

I have an array in php from a recursiveiteratoriterator, It loads fine when I dump the file. When I try to json_encode it and pass it to the browser I get 2 scenarios:

I echo the json_ encode and get the following:

["\/var\/www\/html\/dev\/workspace\/ftpscript\/test\/10MB.zip",
"\/var\/www\/html\/dev\/workspace\/ftpscript\/test\/test.php"]null

If I call it from a remote PHP script (using 2 servers, source (where the script is) and the one taking the info and processing it) from the remote server and json_decode it echo yields:

NULL

The script:

$files = array();
    $startpath = getcwd()."/test/";
    $fileinfos = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($startpath)
    );
    foreach($fileinfos as $pathname => $fileinfo) {
        if (!$fileinfo->isFile()) continue;{
        $files[] .= $pathname;
        }
    }
    $utfEncoded = array_map("utf8_encode", $files );
    echo json_encode($utfEncoded);

I have tried with and without encoding it and it yields the same result. Am I missing something? If it makes a difference I am running php 5.4.38 on apache.

Edit:

I have changed the iteraor around a bit and still yeild the same results... I now have:

function ft_srcscan() {
    $path = getcwd();
    $directory = new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS);
    $iterator = new RecursiveIteratorIterator($directory);
    $files = array();
    foreach ($iterator as $info) {
        $files[$info->getPathname()] = $info->getSize();
    }
    echo json_encode($files);
}

When I put the exact same iterator in a test page by itself along with the encode I get the results here

But when I call it using the method in my class (and it is the only thing running) is here . Ultimately I am trying to get a list of files and file sizes as an array the file being the key and the size being the value.

(More a comment that an answer, but I need more space).

The braces in the expression, that Sverri mentions do nothing and are just confusing. Just leave them out.

Also $files[] .= $pathname; looks weird. $files[] = ... appends to an array, and .= appends to a string. Doing both at the same time makes no sense. PHP seems to ignore the .= . Take it out, too.

So

if (!$fileinfo->isFile()) continue;{
$files[] .= $pathname;
}

becomes

if (!$fileinfo->isFile()) continue;
$files[] = $pathname;

This won't help with your problem most likely. Does the array contain the correct data?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM