使用PHP在.lst播放列表文件每n行后插入广告URL的需求
Here's a PHP solution that does exactly what you need—inserting your 10 ads in order every 5 lines of your playlist, and cycling through the ads once you hit file10.mp3:
<?php // Define your input and output file paths (adjust these to match your setup) $inputFile = 'playlist.lst'; $outputFile = 'playlist_with_ads.lst'; // Read the input playlist file into an array of lines // FILE_IGNORE_NEW_LINES removes trailing newlines; FILE_SKIP_EMPTY_LINES skips blank lines $playlistLines = file($inputFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); // Handle cases where the file can't be read or is empty if (!$playlistLines) { die("Error: Could not read the input file, or the file is empty."); } $outputLines = []; $contentLineCounter = 0; $totalAds = 10; // Total number of ad files we have $currentAdIndex = 0; // Starts at 0 to map to file1.mp3 foreach ($playlistLines as $line) { // Add the original audio URL to our output $outputLines[] = $line; $contentLineCounter++; // Check if we've reached 5 content lines (time to insert an ad) if ($contentLineCounter % 5 === 0) { // Generate the ad URL using the current index (add 1 since ads start at file1.mp3) $adUrl = "file" . ($currentAdIndex + 1) . ".mp3"; $outputLines[] = $adUrl; // Update the ad index, cycling back to 0 after file10.mp3 $currentAdIndex = ($currentAdIndex + 1) % $totalAds; } } // Write the modified playlist to the output file if (file_put_contents($outputFile, implode(PHP_EOL, $outputLines))) { echo "Success! Your playlist with ads has been saved to {$outputFile}"; } else { die("Error: Could not write to the output file. Check file permissions."); } ?>
How this works:
- File Reading: The
file()function reads your.lstfile into an array, skipping empty lines and removing trailing newlines for clean processing. - Counter Logic: We track how many content lines we've added with
$contentLineCounter. Every time this hits a multiple of 5, we insert an ad. - Ad Cycling: The
$currentAdIndexvariable keeps track of which ad to insert next. Using modulo% $totalAdsensures we loop back tofile1.mp3afterfile10.mp3. - Output Writing: We join the modified lines with proper line breaks (
PHP_EOL) and write them to a new file to avoid overwriting your original playlist.
Notes:
- Permissions: Make sure your PHP script has read access to the input file and write access to the directory where you're saving the output file.
- Empty Lines: If you want to include empty lines in your playlist and count them towards the 5-line limit, remove the
FILE_SKIP_EMPTY_LINESflag from thefile()call. - Running the Script: You can run this via the command line (
php playlist_ad_inserter.php) or through a web server (though command line is more straightforward for file processing tasks).
内容的提问来源于stack exchange,提问作者Vikalp
相关产品推荐
相关产品推荐

