I need help in creating a xml file from my php code. I created a function which forms the xml as i want it, but i dont know how to save the formed xml in a file.
Also if you could also tell me, for next time, how can i update the already created xml file.
My code looks like below:
public function create_xml()
{
$output = "<?xml version=\"1.0\" encoding=\"utf-8\" ?> ";
$output .= "<data>";
$output .= "<news>";
$news_articles = new C7_News();
$db = C7_Bootstrap::getDb();
$foxsport_sql = "SELECT headline, link FROM c7_news
WHERE source = 'foxsports' AND category = 'Breaking News'
LIMIT 0,4";
$foxsport_rowset = $db->fetchAll($foxsport_sql);
$data = array();
foreach($foxsport_rowset as $foxsport_row)
{
$output .= "<title>";
$output .= "<description>";
$output .= "<![CDATA[";
$output .= $foxsport_row['headline'];
$output .= "]]>";
$output .= "<link>";
$output .= $foxsport_row['link'];
$output .= "</link>";
$output .= "</title>";
}
$output .= "</news>";
$output .= "</data>";
}
I might be doing something wrong too, plz let me know the best way to create the xml.
Thank you
Zeeshan
I'll add some more information here.
Also if you could also tell me, for next time, how can i update the already created xml file.
You should parse the XML in order to updated, the SimpleXml extension provides and easy to use API for parsing an writing XML files.
I might be doing something wrong too, plz let me know the best way to create the xml.
There are many ways to do this, but I prefer to use PHP as a "template engine" when writing HTML or XML (or any *ML for that matter).
<?php echo "<?xml version=\"1.0\" encoding=\"utf-8\" ?> " ?>
<?php
$news_articles = new C7_News();
$db = C7_Bootstrap::getDb();
$foxsport_sql = "SELECT headline, link FROM c7_news
WHERE source = 'foxsports' AND category = 'Breaking News'
LIMIT 0,4";
$foxsport_rowset = $db->fetchAll($foxsport_sql);
?>
<data>
<news>
<?php foreach($foxsport_rowset as $foxsport_row):
<title>
<description>
<![CDATA[
<?php echo $foxsport_row['headline'] ?>
]]>
</description>
<link><?php echo $foxsport_row['link']</link>
</title>
<?php endforeach; ?>
</news>
</data>
This will output the XML and is a lot easier to read
but i dont know how to save the formed xml in a file.
As for how to save this to a file you should have another PHP file to include this "template" (suppose the template is called xml_template.php):
ob_start();
include dirname(__FILE__) . DIRECTORY_SEPARATOR . 'xml_template.php';
$output = ob_get_clean();
Then you have again the XML string on the $output variable and can do as noted by Vlad.P:
// If file is missing, it will create it.
$file = fopen("file.xml", "w");
fwrite($file, $output);
fclose($file);
Add this at the end of your function.
// If file is missing, it will create it.
$file = fopen("file.xml", "w");
fwrite($file, $output);
fclose($file);
Use
file_put_contents( $file, $output );
You might want to pass in the argument for the path of the file:
$stream->create_xml( $file );
or reason that that should be handled by another method/class, eg
$stream->create_xml();
$stream->save_xml( $file );
Related
My client requested that I implement an affiliate feed with which has the format of XML. However, the file is huge with 650k lines! I tried parsing it using a simpleXML, it worked, but it's extremely slow. As a result, the website sometimes does not load.
<?php
$html = "";
$url = "http://www.digitick.com/rss/distributeur/fluxAffiliation195_815.xml";
$xml = simplexml_load_file($url);
for($i = 0; $i < 10; $i++){
$title = $xml->content->eventList->event[$i]->eventName;
$link = $xml->content->eventList->event[$i]->eventUrl;
$description = $xml->content->eventList->event[$i]->eventPresentation;
$dateStart = $xml->content->eventList->event[$i]->dateStart;
$img = $xml->content->eventList->event[$i]->pictureUrl;
$html .= "<a href='$link'><h3>$title</h3></a>";
$html .= "<img src=$img>";
$html .= "$description";
$html .= "<br />$dateStart<hr />";
}
echo $html;
?>
What can I do to handle the this dynamic file (which updates every morning at 5am?
Thank you in advance!
I would import the file into a SQLite database file with a cron job. Then use SQL to request parts of it in your application. As an alternative cache the generated output and only read the large file once a day.
I have multiple folders with small videos and i need to make a rss feed from them.
Structure of the files is like this:
MainFolder ->
-> File.Summer-> file.summer.p01f1.mp4, file.summer.p01f2.mp4......,file.summer.p02f1.mp4 ,file.summer.p02f2.mp4.... and so on.
-> File.Winter-> file.winter.p01f1.mp4, file.winter.p01f2.mp4......,file.winter.p02f1.mp4,file.winter.p02f2.mp4.... and so on.
What i need is a solution to generate those rss creating a feed like file.summer.p01.rss and the content is all the files containing p01f1, p01f2 then next to file.summer.p02.rss. In all the folders in the path.
I found a solution which makes a single rss with all the files in the folder but i need the rss to be split in parts matching the file names.
It can be a windows bat or a php script.
Thank you.
this is the script i have now:
$list="file.summer";
$part="01";
$ser_dir = 'c:\www\php\movs\\'.$list;
$rss_head = '<rss version="2.0">';
$movs_path="../php/movs/";
$iosser = "/iosser/";
$file_out = $ser_dir."\\".$list.".p".$part.".rss";
$xml = $rss_head. "\n";
$xml .="<channel>"."\n";
foreach (glob($ser_dir."\*.p".$part."*.srt" ,GLOB_NOSORT) as $filename) {
$xml .="<item>". "\n";
$xml .= "<title>".basename($filename, ".srt")."</title>\n";
$filename=basename($filename);
$xml .= "<image>".$movs_path.$list."/".substr($filename, 0,-7).".jpg</image>\n";
$xml .= '<source file="'.$iosser.$list."/".basename($filename,".srt").'.mov"/>'."\n";
$xml .="</item>". "\n";
}
$xml .="</channel>"."\n";
$xml .= "</rss>";
file_put_contents($file_out,$xml);
echo $list ."\n";
echo $part;
Is it possible to save the below output to an XML file as its currently just displayed in the source?
$host = "localhost"; // host name
$user = "#"; // database user name
$pass = "#"; // database password
$database = "#"; // database name
// connecting to database
$connect = #mysql_connect($host,$user,$pass)or die (#mysql_error());
// selecting database
#mysql_select_db($database,$connect) or die (#mysql_error());
// default header(don't delete)
header("Content-Type: text/xml;charset=iso-8859-1");
echo '<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
// mytable = your content table name
$query = #mysql_query("SELECT * FROM urls");
while($row = #mysql_fetch_array($query)){
// [url] = content url
$url = $row['url'];
// [time] = content date
$date = date("Y-m-d", $row['time']);
// NO CHANGES BELOW
echo
'<url>
<loc>' . $url .'</loc>
<lastmod>'. $date .'</lastmod>
<changefreq>daily</changefreq>
<priority>0.8</priority>
</url>
';
}
echo '</urlset>';
I know I can use .htaccess to make the file be seen as an XML format however I want the data to be saved onto an actual file.
You could try changing each echo to append the line to a string variable, for example:
// Instead of
echo '<?xml version="1.0"?>';
echo '<url>';
// etc.
$xml = '<?xml version="1.0"?>';
$xml .= '<url>';
// and so on
Then use one of the file functions to save to a file. file_put_contents is a simple method:
file_put_contents("/path/to/file.xml", $xml);
A more robust solution, if you want to take this further, could be to use the DOM module to build the XML structure:
$document = new DOMDocument("1.0");
$root = $document->createElement("urlset");
$root->setAttribute("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");
$document->appendChild($root);
while ($row = mysql_query($query)) {
$item = $document->createElement("url");
$root->append($item);
// etc.
}
echo $document->saveXML();
NOTE: This answer assumes that by "save file" you mean "trigger the Save As dialog in the browser when someone views the page".
text/xml isn't really the correct content-type. You really should at least application/xml for generic XML or the appropriate content type for XML sub-formats such as RSS or docx.
If you want to trigger a file download dialog in the client browser, then you also need to send a content-disposition header that tells the browser that you want it to download the file and give a preferred filename.
There are some issues with your code that need addressing too.
Overuse of # for error suppression. This is a bad idea for a huge variety of reasons. Remove the # operators and handle any generated errors in a more robust way.
Your character encoding heading specifies one character set (latin-1) but your XML preamble specifies a totally different one (UTF-8). That's a recipe for disaster.
Use output buffers
ob_start();
... do everything you actually did before ...
$content = ob_get_contents();
ob_end_clean();
//Write to a file
file_put_contents('filename.xml', $content);
And thats all...
Using fwrite it should be straight forward :
$f = fopen('data.xml', 'w'); //open a file for writing
fwrite($f, $myxmltext); // write some things to it
fclose($f); // close it when finished
Hi Im trying to create a news feed using php. I have a php code written which connects to the database and retrieves information which is converted into XML. The file is however a .php and when I try to parse it using google reader it dosen't work because it only reads files which are XML. Here's my code:
<?php
header("Content-type: text/xml");
$dept = $_GET['dept'];
require_once ("/var/www/html/http/sass/includes/config.inc.php");
require_once ("sass_news.php");
$sassNews = paginate('sass_news', 'sass_news', $numResults, $offset, $order, $condition);
if($sassNews) {
$xml_output = "<?xml version=\"1.0\"?>\n";
$xml_output .= "<entries>\n";
foreach($sassNews as $newsDetail){
$xml_output .= "\t<entry>\n";
$xml_output .= "\t\t<date>" . $newsDetail->news_start_date . "</date>\n";
$xml_output .= "\t\t<text>" . $newsDetail->news_body_en . "</text>\n";
$xml_output .= "\t</entry>\n";
}
$xml_output .= "</entries>";
echo $xml_output;
}
?>
Try header('Content-disposition: attachment; filename=somename.xml'); at the top of the script. However, if Google Reader is going to allow only URLS which literally end in .xml, then you'll need to reconfigure your server to treat .xml files as PHP scripts and rename this script to whatever.xml.
Have you read the RSS specification, that doesn't look like valid markup to me. It should have an rss node, a channel node and lots of other goodies. Also your content-type should be application/rss+xml
I'm trying to load a remote xml file using php.
This is my code:
$doc = new DOMDocument();
$doc->load($this->xml_file);
$file = $doc->getElementsByTagName('file');
$totalFiles = $file->length;
echo $totalFiles;
The remote xml file link is:
http://localhost/script/index.php?act=xml
This is the code in index.php:
$xml = '<?xml version="1.0"?><MultimediaGallery>';
$query = mysql_query('SELECT `id`,`image`,`desc` FROM `'
.confitem('database','prefix').'table` ORDER BY `id` DESC LIMIT '
.$start.','.$limit);
while($result = mysql_fetch_array($query))
{
$img = unserialize($result['image']);
$desc = unserialize($result['desc']);
$xml .= '<file type="photo"><thumb>'
.settings('site','url').'/'.OPATH_APPFOLDER.'/'
.OPATH_UPFOLDER.'/wallpapers/thumbs/'.$img[0].'</thumb><source>'
.settings('site','url')
.'/'.OPATH_APPFOLDER.'/'.OPATH_UPFOLDER
.'/wallpapers/'.$img[0].'</source><description>'
.$desc[$_SESSION['languagecode']].'</description></file>';
}
$xml .= '</MultimediaGallery>';
header("content-type: text/xml");
echo $xml;
When I visit this xml file link direct in the browser .. it's output to me xml file with this style :
<?xml version="1.0"?><MultimediaGallery><file type="photo"><thumb>http://localhost/script/application/data/wallpapers/thumbs/1116205566_42ce0841ab_s.jpg</thumb><source>http://localhost/script/application/data/wallpapers/1116205566_42ce0841ab_s.jpg</source><description>dfdfdfdf</description></file></MultimediaGallery>
When I execute the xml function which uses the dom to load the xml file I get this error:
Warning: DOMDocument::load()
[domdocument.load]: Extra content at
the end of the document in
http://localhost/script/index.php,
line: 2 in
C:\AppServ\www\script\application\libraries\wallpapers\multimedia.class.php
on line 46
Why is this happening?
Update:
I used dom to create the xml instead:
$xml = new DOMDocument('1.0');
$root = $xml->createElement('MultimediaGallery');
$xml->appendChild($root);
$query = mysql_query('SELECT `id`,`image`,`desc` FROM `'.confitem('database','prefix').'backgrounds` ORDER BY `id` DESC LIMIT '.$start.','.$limit);
while($result = mysql_fetch_array($query))
{
$img = unserialize($result['image']);
$desc = unserialize($result['desc']);
$element = $xml->createElement('file');
$root->appendChild($element);
$attr = $xml->createAttribute('type');
$element->appendChild($attr);
$attr_text = $xml->createTextNode('photo');
$attr->appendChild($attr_text);
$thumb = $xml->createElement('thumb');
$element->appendChild($thumb);
$thumb_text = $xml->createTextNode(settings('site','url').'/'.OPATH_APPFOLDER.'/'.OPATH_UPFOLDER.'/wallpapers/thumbs/'.$img[0]);
$thumb->appendChild($thumb_text);
$source = $xml->createElement('source');
$element->appendChild($source);
$source_text = $xml->createTextNode(settings('site','url').'/'.OPATH_APPFOLDER.'/'.OPATH_UPFOLDER.'/wallpapers/'.$img[0]);
$source->appendChild($source_text);
$description = $xml->createElement('description');
$element->appendChild($description);
$description_text = $xml->createTextNode($desc[$_SESSION['languagecode']]);
$description->appendChild($description_text);
}
header("content-type: text/xml");
echo $xml->saveXML();
But it still gives me the same error. I noticed some thing though, I tried to copy my output xml and save it in a file and read it using the dom parser and the result was that it's read successfully.
But when I try parsing the xml output by the php file then it throws an error.
Your XML is not well-formed. E.g there is something wrong with it.
Try to avoid making XML by concatenating strings because this will happen. You can use DomDocument you make XML as well as read it and manipulate it.
Make sure you have no leading or trailing white space in your XML generating script.
You should also be using CDATA