Run a PHP script when RSS feed updates (cron jobs?) - php

I have a script that sends out a push notification to users based on whats in a PHP file.
This is that file ...the parts that matter ...
$doc = new DOMDocument();
$doc->load('RandomXML Url location here ');
$arrFeeds = array();
foreach ($doc->getElementsByTagName('item') as $node) {
$itemRSS = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue
);
array_push($arrFeeds, $itemRSS);
}
// APPLE APNS EXAMPLE 1
$apns->newMessage(2);
$apns->addMessageAlert($itemRSS['title']);
// $apns->addMessageCustom('acme2', array('bang', 'whiz'));
$apns->queueMessage();
// SEND ALL MESSAGES NOW
$apns->processQueue();
So thats the PHP that sends out the notification. It sends out the notification when this PHP script is loaded.
It loads the first post from the feed and sends it out. I want to send a notification out every time the RSS feed is updated with a new post. If it is updated with a new feed, then I want to run the above code.
So how can I do that and make sure it is run frequently?
I would really like to see what code I need to check if its updated? I don't know how to check for updates though and thats probably the most important part of the script.

Configure Cron to run your script every e.g. 1 hour and in script add code to check is RSS modified.
EDIT:
1. You can configure Cron to run your script every e.g. 1 hour.
2. To the script, add the code to test whether the RSS has been modified.
3. To check whether the feed was changed use the tag. You can save the tag content to txt and compare it.
4. To write tag content you can use SimpleXML and fwrite.

Related

How to save XML API data to database in WordPress once an hour for later use?

I manage the website for PAWS New England, an animal rescue organization who relies heavily on PetFinder. While PetFinder offers an iframe based widget for display your available animals, it breaks the responsive design of the site on smaller screens.
Because of this, I've built custom "Our Dogs" page by using PetFinder's API (XML based).
Unfortunately, the API can run pretty slow at times. I would like to pull data from the API once an hour and store it on the site's mySQL database (it's powered by WordPress), and run the custom page off that instead of the live API data. WordPress's "Transient API" seems like a perfect fit, but I can't for the life of me figure out how to make it work.
After some searching, it seems like the problem may be in PHP's ability (or lack there of) to store XML data. In other words, I may need to convert the data to a string or array first.
I'm now officially stuck. Anyone have any insights on how to save XML data to the WordPress database once and hour, and access that data for use in a function?
Here's my existing code. Thanks in advance!
<?php
function petf_shelter_list( $atts ) {
extract( shortcode_atts( array(
'shelter_id' => '1234',
'api_key' => 'abcdef',
'count' => 150,
'status' => 'A'
), $atts ) );
$xml = simplexml_load_file( "http://api.petfinder.com/shelter.getPets?key=" . $api_key . "&count=" . intval($count) . "&id=" . $shelter_id . "&status=" . $status . "&output=full" );
// Stuff I do with $xml here...
}
add_shortcode('shelter_list','petf_shelter_list');
?>
You can use PHP's XML Parser to deal with the XML portion of your problem.
As for running something every hour, you need to setup a cron job to execute your desired script.

how to create rss feed with autoupdate in Zend

I am quite new in Zend Framework and RSS too. I would like to create on my site RSS feed (of course available to the user in XML file). I have created RssController and corresponding view: rss/index.phtml. XML file generation works fine for me.
In RssControllers I have indexAction:
public function indexAction()
{
$feedData = array(...);
$feed = Zend_Feed::importArray ( $feedData, 'rss' );
$rssFeed = $feed->saveXML();
$fh = fopen("rss.xml", "w");
fwrite($fh, $rssFeed);
fclose($fh);
}
As you can guess, my rss.xml file generates every time when the mysite/rss is visited. I would like to, if this possible, create RSS feed autoupdating in some time interval. And of course, not generating every time when rss subsite is visited. How can I do something like this?
Hum iam not sure what you want but:
you dont need the file handler..
// Disable VIEW/Layout
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$feed = Zend_Feed::importArray ( $feedData, 'rss' );
echo $feed->send();
So the Browser gets "XML" instead of an HTML or what ever..
You have three ways to update your RSS:
1 - Working with an asynchronous system
2 - Insert the URL of your controller into a CRON system (crontab linux or task scheduler windows) and make requests when you want.
3 - Create a Zend_Action_Helper and when the page is accessed, you call this Action.

How do I get FullCalendar to display information from my JSON feed?

I'm setting up an app using FullCalendar (http://arshaw.com/fullcalendar/) that will allow the user to see client scheduling information as well as schedule clients through a management interface.
I want to use a MySQL database to populate an array, and then pass that array in the form of a JSON feed to FullCalendar on an HTML page. Ideally, then, the client information would show up on the HTML page. However, even though my JSON feed is being passed, there are no events on my FullCalendar.
Example JSON feed being passed:
[{"title":"Watson","start":"1333976400","end":"1333980000","allDay":false}]
I'm fairly new to these languages and I would not be surprised if this mistake turn out to be simple.
I would deeply appreciate any help or insight on having these events show up. When I manually feed an array into FullCalendar, it does show the events, but so far my JSON feed has resulted in no information being displayed.
Thank you
For reference:
HTML:
$(document).ready(function() {
$('#calendar').fullCalendar({
events: '/json-events.php'
});
});
PHP:
while ($record = mysql_fetch_array($result)) {
$event_array[] = array(
'id' => $record['id'],
'title' => $record['title'],
'start' => $record['start_date'],
'end' => $record['end_date'],
'allDay' => false
);
}
echo json_encode($event_array);
So the problem, for those searchers that come after me, was that my PHP file had HTML head and body tags. I'm a PHP noob and so I didn't know that would cause it not to work. In order for FullCalendar to display the JSON feed, it must ONLY have PHP code, no HTML. JSONLint.com was invaluable in figuring that out.
I set up a quick example and didn't have any trouble getting this to work:
PHP:
<?php
$record[0]["title"]="Test 1";
$record[1]["title"]="Test 2";
$record[2]["title"]="Test 3";
$record[0]["start_date"]="1333976400";
$record[1]["start_date"]="1333976401";
$record[2]["start_date"]="1333976402";
$record[0]["end_date"]="1333980000";
$record[1]["end_date"]="1333980001";
$record[2]["end_date"]="1333980002";
$record[0]["id"]="1";
$record[1]["id"]="2";
$record[2]["id"]="3";
for ($i=0; $i<3; $i++) {
$event_array[] = array(
'id' => $record[$i]['id'],
'title' => $record[$i]['title'],
'start' => $record[$i]['start_date'],
'end' => $record[$i]['end_date'],
'allDay' => false
);
}
echo json_encode($event_array);
exit;
?>
HTML:
events: '/events.php'
Sample output from the PHP script:
[{"id":"1","title":"Test 1","start":"1333976400","end":"1333980000","allDay":false},{"id":"2","title":"Test 2","start":"1333976401","end":"1333980001","allDay":false},{"id":"3","title":"Test 3","start":"1333976402","end":"1333980002","allDay":false}]
So given that the above works for me and it's really no different to what you have above, you might need to check that the PHP script is actually getting called correctly. Check the Javascript console in Mozilla Firefox or Google Chrome to see if there are any errors thrown when Fullcalendar tries to load the events. Check your web server access/error logs for any mention of the PHP script.
events: '/json-events.php'
should be either
events: './json-events.php'
or
events: 'json-events.php'
Let me know if this helps...
EDIT
I also noticed that in the Json that your are receiving there is no id in the line. There may be something going on between the nameing of you id within the DB comparitively to the name your using in the array. Check it out and see if that is what is going on, because that is one of the properties that are required to pass the event.
EDIT
Try removing the [] from $event_array[] and see what happens... If that doesn't work than I am stumpped... sorry

How do I set up an RSS feed for my hard-coded php & mysql site?

I have absolutely no idea how to start one. Every tutorial I find assumes I have a cms or blog of some sort. Mine's not exactly. I upload everything and coded all my css, html, mysql, php, and such. So how do I create an RSS feed?
I'm guessing I need to use a php include right?
Also I want my RSS feed to be automated if possible. Like all it'll need to know is the title of my page, and then the RSS will send it out to all my subscribers with the link of the page as the only description.
Please post any info you have though, as beggars can't be choosers.
Thanks!
Generate a list of filenames, order them by timestamp, read them, extract title and content snippets, and finally print out an RSS document. Example:
// list + sort
$files = glob("pages/*.html");
$files = array_combine($files, array_map("filemtime", $files));
arsort($files);
// loop + read
foreach ($files as $fn=>$mtime) {
$html = file_get_contents($fn);
preg_match('#<title>([^<]+)', $html, $title) and $title=$title[1];
$rss[] = array(
"link" => $fn,
"pubDate" => $mtime,
"title" => $title,
"description" => substr(strip_tags($html), 0, 100),
);
}
// write RSS
foreach ($rss ...)
Manually create a file containing the RSS XML referencing the pages from your site that you want in your feed. As you add new pages to your site, update that RSS file. The file should be stored along with other files comprising your site.
See the example on Wikipedia for the format: http://en.wikipedia.org/wiki/RSS#Example
Read up on RSS (http://www.w3schools.com/rss/default.asp). you don't have to send anything out; just update the RSS feed, and if they are subscribed the change will propagate through to the end-user. This can either be a semi-automated process that pulls in information as you update your page (why tutorials presuppose a blog or cms), or you can update the feed manually.

PHP - open, read and delete data from a file

I have a file called functions.php.
It contains a lot of data in over 3000 lines.
Somewhere in the middle of this file there is code:
/*****************************************
My Custom Code
*****************************************/
if ( function_exists('my_code') )
my_code(array(
'name' => 'First instance',
'description' => 'Hello, hello.',
));
if ( function_exists('my_code') )
my_code(array(
'name' => 'Second instance',
'description' => 'Haha :)',
));
I'm listing all my_code arrays and I'm getting:
First Instance
Second Instance
Now, what I want to achieve, is, when user clicks X next to "First instance" PHP opens functions.php file in the background, finds the exact function and deletes it without touching anything else.
So after deleting "First Instance" functions.php file should look like this:
/*****************************************
My Custom Code
*****************************************/
if ( function_exists('my_code') )
my_code(array(
'name' => 'Second instance',
'description' => 'Haha :)',
));
Any idea how to achieve this? I know how to open files, write, delete, but I'm not sure how to wipe out not only a single line but a few lines around? :)
If your code is always in the format you described you could read each 5 lines from your file and if it's the instance you want to keep, output them to a string. Then write the string back to the original file.
But again yes, code modifying code IS PAIN. Storing your instances in a data structure such as databases or a formatted file is much better.
I think the best way would be to open the file and loop through the lines. You'll need to match each line of your function, or you would need match the first line and track the number of open and close brackets { } to know when you've reached the end of it.
If a line doesn't match you write that out to a new file. If it does match you ignore it. Then finally you make an system call to do a syntax check on the new file (in case something went wrong with your line matching):
system( "php -l newfile.php", &$retval );
Then check the return value $retval to make sure it was ok (it will be exactly equal to 0). If it is okay then you overwrite functions.php with your new file.
if( $retval === 0 ) {
// the syntax is good
rename( "newfile.php", "functions.php");
}
You would need to set the appropriate paths for this to work.
Now all of that said, this is not a very good idea and I would advise you not to implement it. A better method would be to break your functions out into separate files. Then use an INI config file or a database to keep track of what you should load. Either of those have the ability to be edited. Even a text data file would be better than mucking with the actual code.
Once you know what you're supposed to load then at the beginning require or include the appropriate file.
Here's a simple example of doing it with a database:
$res = mysql_query("SELECT file_name FROM load_functions");
if( mysql_error() ) {
// do something because the query failed
}
else {
while( list($file_name) = mysql_fetch_row($res) ) {
if( file_exists($file_name) ) {
require_once( $file_name );
}
else {
// warn because a file requested didn't exist
}
}
}
Hope that helps

Categories