You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Laravel+league/csv导入TSV文件时遇Undefined array key 'titleType'错误

Fixing "Undefined array key 'titleType'" with league/csv in Laravel

Let's break down what's going on here and fix that frustrating error step by step:

1. The #1 Culprit: Missing TSV Delimiter Configuration

Since you're working with a tab-separated (TSV) file, but the league/csv library defaults to comma-separated values. Without telling it to use tabs as the delimiter, it's probably reading your entire header row as a single key—meaning titleType doesn't actually exist in your record array.

Add this line right after creating the reader:

$reader->setDelimiter("\t");

2. Fix Operator Precedence in Your Condition

Your current if statement has a subtle bug with logic operator order. && runs before ||, so even if $record['titleType'] isn't set, the right side of the || will still try to access it, triggering the error.

Wrap your OR conditions in parentheses to ensure the isset check applies to both values:

if (isset($record['titleType']) && ($record['titleType'] === 'short' || $record['titleType'] === 'movie')) {
    // TODO
}

3. Verify Your Header Names Match Exactly

Double-check that the header in your TSV file exactly matches titleType (no extra spaces, correct casing—capitalization matters!). Add a debug line before the loop to confirm what headers the library is actually reading:

// Print all detected headers to check for mismatches
dd($records->getHeader());

This will reveal if there's a typo (like TitleType, title_type, or title type) that's causing the key to be missing.

Updated Working Code

Putting it all together, your code should look like this:

try { 
    $reader = Reader::createFromPath(public_path() . '/data.tsv', 'r');
    // Critical: Set delimiter for TSV files
    $reader->setDelimiter("\t");
    $reader->setHeaderOffset(0);
    $records = Statement::create()->limit(1)->process($reader);
    
    // Uncomment to debug headers
    // dd($records->getHeader());
    
    foreach ($records as $record) {
        // Fixed condition with proper precedence
        if (isset($record['titleType']) && ($record['titleType'] === 'short' || $record['titleType'] === 'movie')) {
            // TODO
        }
    }
} catch (Exception $e) {
    echo $e->getMessage(), PHP_EOL;
}

内容的提问来源于stack exchange,提问作者wellUKnow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:11:40