how to create rss feed with autoupdate in Zend - php

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.

Related

Import XML products to Prestashop in PHP

I need create a PHP file to import a lot of products from a external source (a distributor) to my Prestashop 1.7.6.
I need to connect with this service "http://www.ferrunion.com/ita/codice/id_service.php" to take the token and when I recive this string I need to connect with this service "http://www.ferrunion.com/ita/codice/catalogo_service.php" to recive the XML file.
This is an example of the structure of the XML:
<![CDATA[
<product>
<id>id<id>
<description>description</description>
<quantity>quantity</quantity>
<confezione>confezione</confezione>
<prezzo_lordo>prezzo acquisto senza sconti</prezzo_acquisto>
<price>price</price>
<info>info</info>
</product>
]]>
The problema are 2:
How can I conncet whit this services in PHP language?
When I have the file, how can import the XML code in my Prestashop's database?
Can you help me with this problem?
Thanks you.
I guess your idea is to develop a Prestashop module and run it using a cron, is that so?
Have you tried to bring the XML file using curl?
From your Prestashop module you must bring the XML via CURL. Once you have the XML loaded you just have to parse (take a look:https://www.w3schools.com/php/php_xml_dom.asp) the file and process each product with the Prestashop API.
Tell me if I can help you.
First create a module
Use module generator to speed up the process
Generate starting module online at https://validator.prestashop.com/generator
1 Download th file
Use curl to download the file to your serwer
See this: https://stackoverflow.com/questions/19248371/how-can-i-save-a-xml-file-got-via-curl
2 Proces the file and insert/update products: 2.1) Through SQL directly to DB2.2) Through PrestaShop API or2.3) Through internal Product Class object (reccomended)
2.1 Create PHP script to load xml and run some customs SQL insert directly (you will need to handle images upload and insert all images to db which is not that trivial). So you would need to populate some or all of this tables:
ps_product
ps_product_lang
ps_product_shop
ps_stock_available
ps_category_product
ps_image
ps_product_download
...
2.2 Use PrestaShop API which will take a resource through URL endpoint and insert it to database internally. This way PrestaShop system will take care of a lot of thing for you, and you will not have to update your script with every new PrestaShop release if they decide to change something in database (or take care of uploading your images and database relations)
2.3 Use Prestashop internal Product class to insert new product wo database.
<?php
// add category first then make reference to category
// configure and add product
$product = new Product;
$product->name = $productName;
$product->ean13 = '';
$product->reference = '';
$product->id_category_default = $getCategoryID;
$product->category = $getCategoryID;
$product->indexed = 1;
$product->description = $description;
$product->condition = 'new';
$product->redirect_type = '404';
$product->visibility = 'both';
$product->id_supplier = 1;
$product->link_rewrite = $link_rewrite;
$product->quantity = $singleStock;
$product->price = round($price - (18.69 / 100) * $price, 2);
$product->active = 1;
$product->add();
Prestahop import script example here
Investigate Product Class here
Working with large XML files
When running php on large XML file do not load all the file to memory with simplexml_load_file() function. Instead use XMLReader combined with SimpleXMLElement.
<?php
// this is not PrestaShop related script. This is pure PHP for manipulating large XML files.
// first load the file with curl and save it on your server in desired location. Then load the file as in example below:
$continueFrom = getLastNumWhereItStoped();
$iCount = 0;
$limit = 1000;
$xml = new XMLReader();
/*
* One-liners to gzip and ungzip a file:
* copy('file.txt', 'compress.zlib://' . 'file.txt.gz');
* copy('compress.zlib://' . 'file.txt.gz', 'file.txt');
*/
$xml->open('compress.zlib://'.'filename.xml.gz');
while($xml->read() && $xml->name != 'product')
{
// skip all not important nodes and stop on "product" node
}
/**
* Run on every "product" node untill it hits 1000
*/
while($xml->name == 'product' && $limit + $continueFrom >= $iCount)
{
if($iCount <= $continueFrom ) continue;
$element = new SimpleXMLElement($xml->readOuterXML());
$product = array(
'name' => strval($element->text->name),
'price' => strval($element->price->buynow),
'parent_category' => strval($element->category->attributes()->parent_category) // category have to be created before product import [maping category is as easy as you might think]
);
// ... do something with $product set create Product Class instance or... send it to API or make SQL insert directly
// if product exists just update the product value you want (for example price and stock quantity).
$iCount++;
$xml->next('product');
unset($element);
}
/* If success */
$continueFrom = setLastNumWhereItStoped($continueFrom + $limit);
3 Schedule the task
Set CRON job tu run the script automatically (download XML) then run update on fields you really need to update. Read your host provider docs on how to do that
DOCS PrestaShop API endpoint
Generate access token
Enable the webservice By default, the webservice feature is disabled on PrestaShop and needs to be switched on before the first use. You can enable it using GUI or programmatically. Both method are presented here: https://devdocs.prestashop.com/1.7/webservice/tutorials/creating-access/
Create a resource
vTo create a resource, you simply need to GET the XML blank data for the resource (example /api/someendpoint?schema=blank), fill it with your changes, and send POST HTTP request with the whole XML as body content to the /api/someendpoint/ URL.
PrestaShop will take care of adding everything in the database, and will return an XML file indicating that the operation has been successful, along with the ID of the newly created customer.
Update a resource
To edit an existing resource: GET the full XML file for the resource you want to change (example /api/someendpoint/1), edit its content as needed, then send a PUT HTTP request with the whole XML file as a body content to the same URL again.
Usefull resources:
https://devdocs.prestashop.com/1.7/webservice/
https://devdocs.prestashop.com/1.7/webservice/getting-started
https://devdocs.prestashop.com/1.7/modules/creation/external-services/
https://drib.tech/programming/parse-large-xml-files-php
Use DB:
https://devdocs.prestashop.com/1.7/development/database/db/
https://devdocs.prestashop.com/1.7/development/database/structure/
How are images stored - path generation explained
Insert image to prestashop database
The topic is quite broad but hope that this will get you started.

Typo3 getting data and convert it to specific xml schema

i am new to typo3, so sorry, if this is too obvious.
I do not expect a complete solution, just the topics i would need to read about in order to solve the task would be perfectly enough. :)
Here the task:
I have a typo 3 installation with job advertisements in it. Now the company wants to publish that data in to a social website, which needs to have the job advertisement data put on a server in an xml feed, which looks like this: http://www.kununu.com/docs#jobfeed. Don't worry about what it says in there, it's just stuff like Job Title, Description etc.
Like i said, i am completely new to this and just have a vague idea.
My thoughts so far were something like this:
I probably need to write a plugin, which pulls the data out of typo3 by the push of a button
That Plugin need to establish a database connection to pull the data (probably it's mysql, but i am not entirely sure yet)
The data need to be formatted, which is either done by some string operations or by some kind of xml handler i assume.
Sidenote: I read something about TypoScript, but i'd like to avoid that, since it's a one time project and probably not worth the time to learn it. For me at least.
Thank you loads for your help in advance.
Cheers
you can handle that (basicly with typoscript). The other part has to come from PHP (F.e. extbase plugin) ... First part creates the XML output. Second part uses my Demo plugin to include data (Pages+special fields) from DB.
Within TS we are able to create a new typeNum. With that you can call your XML. ( ?type=1234 ) Within the BE you can select each page for output.
If you need help just contact me. I would send you the plugin.
sitemap = PAGE
sitemap {
typeNum = 1234
config {
# Set charset to utf-8
metaCharset = utf-8
# Deactivate TYPO3 Header Code
disableAllHeaderCode = 1
# Content-type settings
additionalHeaders = Content-type:text/xml;charset=utf-8
# Do not cache the page
no_cache = 1
# No xhtml cleaning trough TYPO3
xhtml_cleaning = 0
}
10 = USER_INT
10 {
userFunc = TYPO3\CMS\Extbase\Core\Bootstrap->run
pluginName = Sitemap
extensionName = Srcxmlprovider
controller = Sitemap
vendorName = Sourcecrew
action = exportXml
switchableControllerActions {
Sitemap {
1 = exportXml
}
}
}
}
Ich habe die EXT noch schnell ins TER gepushed. Ein Tutorial liegt innerhalb.
http://typo3.org/extensions/repository/view/srcxmlprovider

How can I get an id from a simplepie post which can be used to look it up later?

I've recently started developing a portfolio website which I would like to link to my wordpress blog using simplepie. It's been quite a smooth process so far - loading names and descriptions of posts, and linking them to the full post was quite easy. However, I would like the option to render the posts in my own website as well. Getting the full content of a given post is simple, but what I would like to do is provide a list of recent posts which link to a php page on my portfolio website that takes a GET variable of some sort to identify the post, so that I can render the full content there.
That's where I've run into problems - there doesn't seem to be any way to look up a post according to a specific id or name or similar. Is there any way I can pull some unique identifier from a post object on one page, then pass the identifier to another page and look up the specific post there? If that's impossible, is there any way for me to simply pass the entire post object, or temporarily store it somewhere so it can be used by the other page?
Thank you for your time.
I stumbled across your question looking for something else about simplepie. But I do work with an identifier while using simplepie. So this seems to be the answer to your question:
My getFeedPosts-function in PHP looks like this:
public function getFeedPosts($numberPosts = null) {
$feed = new SimplePie(); // default options
$feed->set_feed_url('http://yourname.blogspot.com'); // Set the feed
$feed->enable_cache(true); /* Enable caching */
$feed->set_cache_duration(1800); /* seconds to cache the feed */
$feed->init(); // Run SimplePie.
$feed->handle_content_type();
$allFeeds = array();
$number = $numberPosts>0 ? $numberPosts : 0;
foreach ($feed->get_items(0, $number) as $item) {
$singleFeed = array(
'author'=>$item->get_author(),
'categories'=>$item->get_categories(),
'copyright'=>$item->get_copyright(),
'content'=>$item->get_content(),
'date'=>$item->get_date("d.m.Y H:i"),
'description'=>$item->get_description(),
'id'=>$item->get_id(),
'latitude'=>$item->get_latitude(),
'longitude'=>$item->get_longitude(),
'permalink'=>$item->get_permalink(),
'title'=>$item->get_title()
);
array_push($allFeeds, $singleFeed);
}
$feed = null;
return json_encode($allFeeds);
}
As you can see, I build a associative array and return it as JSON what makes it really easy using jQuery and ajax (in my case) on the client side.
The 'id' is a unique identifier of every post in my blog. So this is the key to identify the same post also in another function/on another page. You just have to iterate the posts and compare this id. As far as I can see, there is no get_item($ID)-function. There is an get_item($key)-function but it is also just taking out a specific post from the list of all posts by the array-position (which is nearly the same way I suggest).

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.

Drupal: Inserting fivestar widget in an external php file

I have been trying to load fivestar module and show the rating widget of the selected node in an external php file. I have gotten the rating widget displayed on the page but it only displays degraded version of the widget (non-JavaScript, dropdown widget and "Rate" button) I looked into the source code of the page but the javascript for fivestar module was not loaded. I have tried to load javascript using following functions but had no luck:
fivestar_add_js();
$path = drupal_get_path('module','fivestar');
drupal_add_js($path.'/js/fivestar.js', 'inline', 'footer');
The following is the code in the php file:
//require the bootstrap include
require_once 'includes/bootstrap.inc';
//Load Drupal
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
fivestar_add_css();
// I have used one of the following two functions one at a time to test.
fivestar_add_js();
$path = drupal_get_path('module','fivestar');
drupal_add_js($path.'/js/fivestar.js', 'inline', 'footer');
$book = $_GET["book"];
$chap = $_GET["chap"];
$prob = $_GET["prob"];
$string = $book.'/'.$chap.'/'.$prob;
$query = "SELECT ctcr.nid FROM content_type_comments_ratings AS ctcr WHERE ctcr.field_problem_value = '".$string."'";
$result=db_query($query);
$row = db_fetch_array($result);
if(isset($row['nid']))
{
$nid = $row['nid'];
node_load(FALSE, NULL, TRUE);
$fivestar = node_load($nid, NULL, TRUE);
if (function_exists('fivestar_widget_form')) print fivestar_widget_form($fivestar);
}
If you could give me a hint or direct me to some reading on the web, I would appreciate it. Thank you very much in advance.
By doing all this on an 'external' page/file, you circumvent the Drupal theming system - drupal_add_js() (and fivestar_add_js(), as it is just using that in the end) do not output the script tags themselves, but simply ensure that they will be included in the $scripts variable in page.tpl.php, which is then responsible to print that variables content. As you do not go through the page template, you get no script tags.
You could do a print drupal_get_js(); in your external file to output the scripts added via drupal_add_js() as a quick fix, but note that this will output all the default drupal js files as well, which might be more than you need (but might as well contain other scripts needed by fivestar, e.g. jquery). Alternatively, you'll have to create the needed script tags yourself.
As for hints on what to read, it is difficult to point you to something particular, but you might want to read up on the theming system in general.

Categories