不能在wordpress functions.php中使用php fopen()函数

时间:2014-02-24 14:22:18

标签: php wordpress csv fopen

我想在 functions.php 中简单地运行fopen(),并且还在 test.php wordpress模板文件中尝试了它。

但它不起作用。如果我将test.php文件和csv文件移动到主题文件夹之外的位置,那么它将首次运行。

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

这是我在主题文件中的文件夹结构...

enter image description here

为什么它不起作用的任何想法?

2 个答案:

答案 0 :(得分:1)

您需要使用完整的文件路径而不是相对路径。

使用WordPress函数get_template_directory()获取模板目录的路径。从那里添加文件的路径。

变化:

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

要:

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

答案 1 :(得分:0)

最后让我的代码在NathanDawnson的帮助下工作。

某些原因,function.php不喜欢相对路径。这是修复......

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

查看完整的代码。

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