Create external XML file on page load - php

Basically I've set up a WPAlchemy metabox for the custom post type 'dealer' and I want to generate an XML file that contains formatted meta data from all of the dealer posts so that the data can be used for markers on a google map. Here's what I have in my functions.php file so far based off of Write to XML file using fopen in Wordpress
<?php function markers_xml() {
if ($_POST['post_type'] == 'es_dealer') {
$xml = new SimpleXMLElement('<xml/>');
$markers = get_posts('post_type=es_dealer&posts_per_page=-1');
$xml->addChild('markers');
foreach($markers as $i=>$marker) {
$name = get_the_title($marker->ID);
$lat = get_post_meta($marker->ID, 'lat', true);
$lng = get_post_meta($marker->ID, 'long', true);
$xml->markers->addChild('marker');
$xml->markers->marker[$i]->addAttribute('name', $name);
$xml->markers->marker[$i]->addAttribute('lat', $lat);
$xml->markers->marker[$i]->addAttribute('lng', $lng);
}
$file = 'http://encode-design.com/wp-content/uploads/test.xml';
$open = fopen($file, 'w') or die ("File cannot be opened.");
fwrite($open, $xml->asXML());
fclose($open);
}
}
add_action( 'save_post', 'markers_xml' ); ?>
When I save a dealer post I don't get a message saying 'File cannot be opened.' but there are no changes to the xml file either. I've set the xml file and the uploads folder permissions to 777 and fopen is enabled on my server. What am I missing? Any help would be much appreciated!

Add this code to check whether writing to the file is successful.
if(!fwrite($open, $xml->asXML()))
{
echo 'error';
}
else
{
echo 'success';
}

I switched to file_put_contents() instead of fopen, fwrite, and fclose and it did the trick! Also simplified my file path.
<?php
$xml = new SimpleXMLElement('<xml/>');
$markers = get_posts('post_type=es_dealer&posts_per_page=-1');
$xml->addChild('markers');
foreach($markers as $i=>$marker) {
global $dealer_mb;
$meta = $dealer_mb->the_meta($marker->ID);
$name = get_the_title($marker->ID);
$lat = $meta['lat'];
$lng = $meta['long'];
$xml->markers->addChild('marker');
$xml->markers->marker[$i]->addAttribute('name', $name);
$xml->markers->marker[$i]->addAttribute('lat', $lat);
$xml->markers->marker[$i]->addAttribute('lng', $lng);
}
$file = 'testing.xml';
$current = $xml->asXML();
file_put_contents($file,$current);
?>

Related

generate html file and download it with php

First goal: Create an index.html file and create a link to download the generated file
The issue here is when i click to generate new file the downloaded file is always the same and isnt updated
the variable $content has insite an entire html page with <headers><aside> and <sections>
I have the following code
if( empty( $error )){
echo "<h3>File generated</h3>";
$my_file = 'index.html';
if (file_exists($my_file)) {
if(unlink($my_file)){
};
$new_file = 'index.html';
$handle = fopen($new_file, 'w') or die('Cannot open file: '.$new_file);
$data = $content;
fwrite($handle, $data);
fclose($handle);
echo "<a download='index.html' href='index.html'><b class='download'>Download</b></a>";
} else {
$new_file = 'index.html';
$handle = fopen($new_file, 'w') or die('Cannot open file: '.$new_file);
$data = $content;
fwrite($handle, $data);
fclose($handle);
echo "<a download='index.html' href='index.html'><b class='download'>Download</b></a>";
}
hi i think it's will be work if variable $content will be contain correct data and you have permission to read, update, create file. in code I use file_put_contents function for minimize your code
if( empty( $error )){
echo "<h3>File generated</h3>";
$my_file = 'index.html';
file_put_contents($my_file, $content);
echo "<a download='index.html' href='index.html'><b class='download'>Download</b></a>";
}
UPDATE:
Are you sure that you have correctly generated content and the $content always contains different value?

Odd Behavior when appending JSON file using PHP

So I have a JSON file containing basketball player information in the following format:
[{"name":"Lamar Patterson","team":1,"yearsLeft":0,"position":"PG","PPG":17},{"name":"Talib Zanna", "team":1,"yearsLeft":0,"position":"SF","PPG":13.1},....]
I want a user to be a able to add their own custom players to this file. To do this i try the following:
<?php
$json = file_get_contents('json/players.json');
$info = json_decode($json, true);
$info[] = array('name'=>$name, 'team'=>$team, 'yearsLeft'=>4, 'position'=>$position, 'PPG'=>$ppg);
file_put_contents('json/players.json', json_encode($info));
?>
This "sort of" works. But when I check the JSON file, I find that there are 3 new entries rather than 1:
{"name":"","team":null,"yearsLeft":4,"position":"","PPG":""},{"name":"","team":"3","yearsLeft":4,"position":"","PPG":""},{"name":"Jeff","team":null,"yearsLeft":4,"position":"C","PPG":"23"}
assuming $name="Jeff" $team=3 and $ppg=23 (populated via POST submission).
What's going on and how can I fix it?
You could try doing the following:
Untested code
<?php
if(!empty($name) && !empty($team) && !empty($position) && !empty($ppg)) {
$fh = fopen('json/players.json', 'r+') or die("can't open file");
$stat = fstat($fh);
ftruncate($fh, $stat['size']-1);//removes last ] char
fclose($fh);
$fh = fopen('json/players.json', 'a');
$info = array('name'=>$name, 'team'=>$team, 'yearsLeft'=>4, 'position'=>$position, 'PPG'=>$ppg);
fwrite($fh, ','.json_encode($info).']');
fclose($fh);
}
?>
This will append the only the new json to the file instead of opening the file, making php parse all the json and then writing it to the file again. In addition to that it will only store the data if the variables actually contain data.
Try this:
<?php
//get the posted values
$name = $_POST['name'];
$team = $_POST['team'];
$position = $_POST['position'];
$ppg = $_POST['ppg'];
//verify they're not empty
if(!empty($name) && !empty($team) && !empty($position) && !empty($ppg)) {
//Open the file
$fh = fopen('json/players.json', 'r+') or die("can't open file");
//get file info/stats
$stat = fstat($fh);
//final desired size after trimming the trailing ']'
$size = $stat['size']-1;
//file has contents? then remove the trailing ']'
if($size>0) ftruncate($fh, $size);
//close the current handle
fclose($fh);
// reopen the file for append
$fh = fopen('json/players.json', 'a');
//build your data array
$info = array('name'=>$name, 'team'=>$team, 'yearsLeft'=>4, 'position'=>$position, 'PPG'=>$ppg);
//if this is not the first item on file
if($size>0) fwrite($fh, ','.json_encode($info).']'); //append with comma
else fwrite($fh, '['.json_encode($info).']'); //first item on file
fclose($fh);
}
?>
Maybe your php config is not set to convert the post/get variables to global variables. This happened to me a couple of times so I rather create the variables I'm expecting from the post/get request. Also watch out for the page encoding, from personal experience you could be getting empty strings there.

How to I create a new file with php Post Data

I am working on this website(for minecraft servers) that when you enter in a few things about your server, it will upload the info onto the list of servers. The thing is, I am a complete noob at PhP.
Here is my form code:
http://pastie.org/8061636
And here is my php code:
<?php
$name = $_POST['sName'];
$ip = $_POST['sIp'];
$port = $_POST['sPort'];
$desc = $_POST['sDesc'];
$finalName = $ip."(".$port.").txt";
$file = fopen($finalName, "w");
$size = filesize($finalName);
if($_POST['submit']) fwrite($file, "$name, $ip, $port, $desc");
header( 'Location: http://www.maytagaclasvegas.com/uniqueminecraftservers/upload/' ) ;
?>
Now what I am trying to do it get do is create a new file name using $ip and $port, and put this into a table. Can anyone help a newbie out? Thanks
Try something like this
file_put_contents("/path/to/files/".$ip."-".$port.".dat",
$_POST['sName'].",".$_POST['sIp'].",".$_POST['sPort'].",".
$_POST['sDesc']);
Then to create your table you would need to do something like this.
$files = glob("/path/to/files/*.dat");
echo "<table>";
foreach($files as $file){
echo "<tr><td>".implode("</td><td>", explode(",",file_get_contents($file),4))."</td></tr>";
}
echo "</table>";
It would be a lot safer though to just use a database.
Try this one:
<?php
$name = $_POST['sName'];
$ip = $_POST['sIp'];
$port = $_POST['sPort'];
$desc = $_POST['sDesc'];
$finalName = $ip."(".$port.").txt";
if($_POST['submit']) {
$file = $finalName;
// Append a new person to the file
$content = "$name, $ip, $port, $desc";
// Write the contents back to the file
file_put_contents($file, $current);
}
?>
Note: Be sure you have write (may be 777 in linux) permission on your folder where you are saving the file.

Trouble getting the content when generating an XML file with Wordpress for Google Maps

I needed to generate an XML file through Wordpress to be used for generating markers on a Google Map.
I modified a function I found here: Write to XML file using fopen in Wordpress
The function runs whenever a post is modified.
The map side of things is working fine. I can generate an XML file which has a title and longitude and latitude for each entry and they are properly plotted on the map.
However I can't seem to get the post content, which I want to use for the address. I can't even get the content just to echo for testing. I've tried encoding the html in case that was conflicting with the XMl, but nothing. Seems to just not be getting any content. Yes I have made sure the posts have content although I am open to the idea I may have missed something simple :-p
My function is below.
add_action( 'save_post', 'markers_xml' );
function markers_xml(){
if ($_POST['post_type'] == 'places-to-eat')
{
$xml = new SimpleXMLElement('<xml/>');
$markers = get_posts( array( 'post_type'=>'places-to-eat', 'numberposts'=>-1 ) );
$xml->addChild('markers');
foreach($markers as $i=>$marker){
$name = get_the_title($marker->ID);
$address = get_the_content($marker->ID);
$address = htmlentities($address);
$lat = get_post_meta($marker->ID, 'the-lat', true);
$lng = get_post_meta($marker->ID, 'the-lng', true);
$xml->markers->addChild('marker');
$xml->markers->marker[$i]->addChild('name', $name);
$xml->markers->marker[$i]->addChild('address', $address);
$xml->markers->marker[$i]->addChild('lat', $lat);
$xml->markers->marker[$i]->addChild('lng', $lng);
}
$file = '/public_html/wp-content/uploads/test.xml';
$open = fopen($file, 'w') or die ("File cannot be opened.");
fwrite($open, $xml->asXML());
fclose($open);
}
}
The title and content are already available to you through the get_posts(). There is no need to use get_the_title() or get_the_content(). The return values for the get_posts() is stated in the get_post() documentation. This shows you the data available.
Try this.
foreach($markers as $i=>$marker){
//replace this
//$name = get_the_title($marker->ID);
//with this
$name = $marker->post_title;
//replace this
//$address = get_the_content($marker->ID);
//with this
$address = $marker->post_content;

Write to XML file using fopen in Wordpress

I'm trying to write to an XML file in the uploads folder in my Wordpress directory. This XML needs to update each time the client updates or creates a new post using a custom post_type I created.
Here is the code:
<?
add_action( 'save_post', 'producers_xml' );
function producers_xml(){
if ($_POST['post_type'] == 'producer')
{
$xml = new SimpleXMLElement('<xml/>');
$producers = get_posts( array( 'post_type'=>'producer', 'numberposts'=>-1 ) );
$xml->addChild('producers');
foreach($producers as $i=>$producer){
$name = get_the_title($producer->ID);
$owner = get_post_meta($producer->ID, '_producer_contact_name', true);
$phone = get_post_meta($producer->ID, '_producer_phone', true);
$fax = get_post_meta($producer->ID, '_producer_fax', true);
$email = get_post_meta($producer->ID, '_producer_email', true);
$website = get_post_meta($producer->ID, '_producer_website', true);
$address = get_post_meta($producer->ID, '_producer_address', true);
$xml->producers->addChild('producer');
$xml->producers->producer[$i]->addChild('name', $name);
$xml->producers->producer[$i]->addChild('owner', $owner);
$xml->producers->producer[$i]->addChild('phone', $phone);
$xml->producers->producer[$i]->addChild('fax', $fax);
$xml->producers->producer[$i]->addChild('email', $email);
$xml->producers->producer[$i]->addChild('website', $website);
$xml->producers->producer[$i]->addChild('address', $address);
}
$file = '../../../uploads/producers.xml';
$open = fopen($file, 'w') or die ("File cannot be opened.");
fwrite($open, $xml->asXML());
fclose($open);
}
}
?>
The problem I am having is that it keeps giving me the "File cannot be opened." error that I supplied. My uploads folder (and all enclosed items) have full permissions (777). I've tested my code locally and it works, but I can't get it to open that file on the remote server. I don't have root access to it so I can't change permissions on anything before httpdocs.
I should also mention that fopen is enabled on the server.
EDIT: allow_url_fopen is enabled but allow_url_include is disabled.
Anybody know what my problem is?
Thanks
Try using an absolute path (full path), alongside other checks see:
$file = 'home/my/path/uploads/producers.xml'; //Absolute path
if(is_file($file) && is_readable($file)){
$open = fopen($file, 'w') or die ("File cannot be opened.");
fwrite($open, $xml->asXML());
fclose($open);
}

Categories