我想在我的网站上显示视频。在文件中我有网址(分隔符|) 我不能这样做: 从.txt中的文本做数组。 从数组中获取4个随机网址。
youtube_vids.txt
https://www.youtube.com/embed?v=oavMtUWDBTM|
https://www.youtube.com/embed?v=dQw4w9WgXcQ|
https://www.youtube.com/embed?v=djV11xsamQ|
https://www.youtube.com/embed?v=Tj75ArXbc914|
https://www.youtube.com/embed?v=9jK-NcRmVcw|
https://www.youtube.com/embed?v=n4RjJKhq5ho|
https://www.youtube.com/embed?v=6Ejga4kJUts|
我在这里停了下来:
$vid_list = file('youtube_vids.txt');
任何人都可以帮助我吗?非常感谢!
答案 0 :(得分:1)
file()函数用换行符分隔数组,所以|分隔符未使用,必须进行修剪:
$vid_list = file('youtube_vids.txt');
shuffle($vid_list);
for ($i = 0; $i < 4; $i++) {
// Trim any newline characters
$url = trim($vid_list[$i]);
// Then trim the 'separator'
$url = trim($url, '|');
echo $url . "<br/>";
}
答案 1 :(得分:1)
解决方案是:
file()
array_rand()
explode()
并从数组中提取网址所以你的代码应该是这样的:
$lines = file('youtube_vids.txt');
$rand_array = array_rand($lines, 4);
$random_urls = array();
foreach ($rand_array as $line) {
$random_urls[] = explode("|",$lines[$line])[0];
}
// display $random_urls array
echo "<pre>";
print_r($random_urls);
echo "</pre>";
答案 2 :(得分:1)
$videoArray = file('youtube_vids.txt');
$randomIndexes = array_rand($videoArray, 4);
foreach ($randomIndexes as $index) {
echo '<iframe width="420" height="315" src="'.preg_replace( "/\r|\n/", "", str_replace('|','',$videoArray[$index])).'"></iframe>';
}
将输出
<iframe width="420" height="315" src="https://www.youtube.com/embed?v=dQw4w9WgXcQ"></iframe>
<iframe width="420" height="315" src="https://www.youtube.com/embed?v=oavMtUWDBTM"></iframe>
<iframe width="420" height="315" src="https://www.youtube.com/embed?v=6Ejga4kJUts"></iframe>
<iframe width="420" height="315" src="https://www.youtube.com/embed?v=dQw4w9WgXcQ"></iframe>
答案 3 :(得分:1)
$filename = "file.txt"; //Input Text File With Separators
if(file_exists($filename)) { //Check if file exists
$myfile = fopen($filename, "r") or die("Unable to open file!"); //Reading file
$fileData = fread($myfile,filesize($filename)); //Save file data in a variable
$splitData = explode("|", $fileData); //Split file data using separators
$randLinks = array_rand($splitData, 4); // Get 4 random indices from splitData array
foreach($randLinks as $randLink) { // Foreach index
echo $splitData[$randLink] . "<br>"; // Get url
}
fclose($myfile); //Don`t forget to close the file
}