I have this php which loads rss feed for Economic news. Is it possible to play a sound when the rss feed adds a new title? I have not tried anything yet because i have no idea how to do it. I suppose what i need to do is store the variable from title and then compare it and after that call a function on javascript to play the sound.
<?php
$rss = new DOMDocument();
$rss->load('https://rss.dailyfx.com/feeds/alerts/');
$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
$item = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
);
array_push($feed, $item);
}
$limit = 5;
for($x=0;$x<$limit;$x++) {
$title = str_replace(' & ', ' & ', $feed[$x]['title']);
$description = $feed[$x]['desc'];
$date = date('l F d, Y, H:m', strtotime($feed[$x]['date']));
echo '<p><strong><a " title="'.$title.'">'.$title.'</a></strong><br />';
echo '<small><em style="color:red; text-align:center;"> '.$date.'</em> </small></p>';
}
?>
One of the way I know is to use Jquery/Ajax Ensure you have jquery file jquery.min.js in your directory. I have also amended your php code to make it work. let me know if you have any issue.
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//$('#submit').click(function(){
var title='rssfeed';
$('#loader').fadeIn(400).html('<span>Please Wait, loading.....</span>');
//you can send data if you like
var datasend = "title="+ title;
$.ajax({
type:'POST',
url:'rssfeed.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
if(msg=='success'){
alert('message successfully loaded');
(new Audio('https://notificationsounds.com/soundfiles/8b16ebc056e613024c057be590b542eb/file-sounds-1113-unconvinced.mp3')).play();
}else{
alert('message loading failed');
}
$('#loader').hide();
}
});
//})
});
</script>
//Display a loading message...
<div id="loader"></div>
Your php code becomes
<?php
// ensure there is no error message
error_reporting(0);
$rss = new DOMDocument();
$rss->load('https://rss.dailyfx.com/feeds/alerts/');
$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
$item = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
);
array_push($feed, $item);
}
$limit = 5;
for($x=0;$x<$limit;$x++) {
$title = str_replace(' & ', ' & ', $feed[$x]['title']);
$description = $feed[$x]['desc'];
$date = date('l F d, Y, H:m', strtotime($feed[$x]['date']));
//echo '<p><strong><a " title="'.$title.'">'.$title.'</a></strong><br />';
//echo '<small><em style="color:red; text-align:center;"> '.$date.'</em> </small></p>';
//They should be only one echo to trigger success or failure actions in other to play the sound at ajax.
echo "success";
}
?>