Lynob
Lynob

Reputation: 5337

How to echo php array in html5 audio and video players?

I have two php arrays, array a contain strings representing paths for mp3 files on server. Array b contains strings representing paths for mp4 files.

Lets take this simple example

$test = 'a.mp3';
$var = json_encode($test);
echo '<audio controls>';
echo '<source src=<?php $var ?> type="audio/mpeg">';
echo 'Your browser does not support the audio element.';
echo '</audio>';

this didn't work. This didn't work either

$test = 'a.mp3';
$var = json_encode($test);
echo '<audio controls>';
echo '<source src=$var type="audio/mpeg">';
echo 'Your browser does not support the audio element.';
echo '</audio>';

With quotes, without quotes, nothing works. I even tried without json_encode and didn't work obviously. so how to echo variables into html5 players? I will then be able to loop through the array, generating a playlist.

Upvotes: 1

Views: 1245

Answers (4)

Peternak Kode Channel
Peternak Kode Channel

Reputation: 586

In php you are not allowed to make the php open tag <?php again. for this line echo '<source src=<?php $var ?> type="audio/mpeg">'; you should just make code like this echo '<source src="$var" type="audio/mpeg">';

Upvotes: 0

Jeff Puckett
Jeff Puckett

Reputation: 40971

variables don't expand inside single ' quotes, only inside double " quotes, (unless the single quotes are ultimately inside double quotes) so your second approach should have almost worked:

$test = 'a.mp3';
$var = json_encode($test);
echo '<audio controls>';
echo "<source src=$var type='audio/mpeg'>";
echo 'Your browser does not support the audio element.';
echo '</audio>';

However, I don't understand why you're JSON encoding the file name. If the a.mp3 is in the same folder as this file, then just:

$test = 'a.mp3';
echo '<audio controls>';
echo "<source src='$test' type='audio/mpeg'>";
echo 'Your browser does not support the audio element.';
echo '</audio>';

Upvotes: 2

Aditya
Aditya

Reputation: 851

 $test = 'a.mp3';
 $var = json_encode($test);
echo '<audio controls>';
echo "<source src=$var type='audio/mpeg'>";
echo 'Your browser does not support the audio element.';
echo '</audio>';

Use double quote when you want to print the variable

Upvotes: 2

Abi Narayan
Abi Narayan

Reputation: 66

$arrays = array(
    'mp3' => 'http://example.com/file/filename.mp3',
    'mp4' => 'http://example.com/file/filename.mp4',
);

echo '<audio controls>';
echo '<source src='.$arrays['mp3'].' type="audio/mpeg">';
echo 'Your browser does not support the audio element.';
echo '</audio>';

Upvotes: 0

Related Questions