Cant use php fopen() function in wordpress

2019-03-03 11:46发布

问题:

I am trying to simple run fopen() in the functions.php, and have also tried it in a test.php wordpress template file.

But it does not work. If I move the test.php file and csv file to a location outside the theme folder then it works first time.

function csv_to_array($filename='', $delimiter=',')
{
    if(!file_exists($filename) || !is_readable($filename))
        return FALSE;

    $header = NULL;
    $data = array();
    if (($handle = fopen($filename, 'r')) !== FALSE)
    {
        while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
        {
            if(!$header)
                $header = $row;
            else
                $data[] = array_combine($header, $row);
        }
        fclose($handle);
    }
    return $data;
}

echo '<pre>';
var_dump(csv_to_array('csv/nationality-codes.csv'));
echo '</pre>';

This is my folder structure in the theme file...

Any ideas why it does not work?

回答1:

You need to use the full file path instead of a relative one.

Use the WordPress function get_template_directory() to get the path to your template directory. From there add the path to your file.

Change:

var_dump(csv_to_array('csv/nationality-codes.csv'));

To:

var_dump( csv_to_array( get_template_directory() . 'csv/nationality-codes.csv' ) );


回答2:

Finally got my code working with the help from NathanDawnson.

Some reason functions.php did not like relative path. This was the fix...

get_template_directory() . '/csv/nationality-codes.csv'

See full code working.

// csv to array
function csv_to_array($filename='', $delimiter=',')
{
    if(!file_exists($filename) || !is_readable($filename))
        return FALSE;

    $header = NULL;
    $data = array();
    if (($handle = fopen($filename, 'r')) !== FALSE)
    {
        while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
        {
            if(!$header)
                $header = $row;
            else
                $data[] = array_combine($header, $row);
        }
        fclose($handle);
    }
    return $data;
}


// rider nationality
function motocom_rider_nationality( $field )
{

    // reset choices
    $field['choices'] = array();

    // get the textarea value from options page without any formatting
    $choices = csv_to_array( get_template_directory() . '/csv/nationality-codes.csv' );

    $field['choices'] = array(
        null => 'Select nationality...'
    ); 

    // loop through array and add to field 'choices'
    if( is_array($choices) )
    {

        foreach( $choices as $choice )
        {

            $label = $choice['Country'];
            $value = $choice['A3'];

            $field['choices'][ $value ] = $label . ' [' . $value . ']';

        }
    }

    // Important: return the field
    return $field;

}
add_filter('acf/load_field/name=rider_nationality', 'motocom_rider_nationality');