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);
}
Related
I am trying to get the API data from a cache file if there already was the same request recently. Everything works fine but I am just not able to get the content from the cache file even tho it is there. I can't find an error. I hope u can help me.
$url = /* API URL */;
function getJson($url) {
$cacheFile = 'cache' . DIRECTORY_SEPARATOR . md5($url) . '.json';
if (file_exists($cacheFile)) {
$fh = fopen($cacheFile, 'r');
$cacheTime = filemtime($cacheFile);
if ($cacheTime > strtotime('-60 minutes')) {
$json = fread($fh);
return $json;
}
fclose($fh);
unlink($cacheFile);
}
$json = file_get_contents($url);
$fh = fopen($cacheFile, 'w');
fwrite($fh, $json);
fclose($fh);
return $json;
}
$datab = getJson($url);
$data = json_decode($datab, true);
print_r($data);
Il you dont check for your error log or display errors on screen you gonna have a bad time finding its.
Here you have a $cacheFile which should be a $cachePath, so prefix with './' or better DIR
Then you call fread without second parameter, and so on...check your error log, enable all errors.
You must specify the length that needs to be read in fread.
Use:
if (file_exists($cacheFile)) {
$fh = fopen($cacheFile, 'r');
$cacheTime = filemtime($cacheFile);
if ($cacheTime > strtotime('-60 minutes')) {
$json = fread($fh,filesize($cacheFile));
fclose($fh); //Remember to release resources
return $json;
}
fclose($fh);
unlink($cacheFile);
}
Alternatively use file_get_contents($cacheFile) to get the whole file without the need for an fopen first.
I am downloading the image from URL using file_get_contents function. But in some case I get the error like this
"file_get_contents(http://www.aaaaa.com/multimedia/dynamic/02456/RK_2456652g.jpg): failed to open stream: HTTP request failed!".
Only for some of the URL am getting this error, other images are easily downloaded using this code.
I am getting this error when I run this code in cron. But when I manually downloading the image from same URL its downloading. Can anyone please help me to solve this problem.
My code is
$arr="http://www.aaaa.com/multimedia/dynamic/02077/saibaba_jpg_2077721g.jpg";
$file = basename($arr);
$date = date('Ymd');
$id=2225;
if (!file_exists('../media/'.$date)) {
$path=mkdir('../media/'.$date, 0777, true);
}
if (!file_exists('../media/'.$date.'/'.$id)) {
$path=mkdir('../media/'.$date.'/'.$id, 0777, true);
}
//Get the file
$content= file_get_contents($arr);
//Store in the filesystem.
$fp = fopen('../media/'.$date.'/'.$id.'/'.$file, "w");
fwrite($fp, $content);
fclose($fp);
If you are execute your function then you must provide full path to of your file.LIKE
$arr="http://www.aaaa.com/multimedia/dynamic/02077/saibaba_jpg_2077721g.jpg";
$file = basename($arr);
$date = date('Ymd');
$id=2225;
if (!file_exists('/var/www/path_to_Your_folder/media/'.$date)) {
$path=mkdir('/var/www/path_to_Your_folder/media/'.$date, 0777, true);
}
if (!file_exists('/var/www/path_to_Your_folder/media/'.$date.'/'.$id)) {
$path=mkdir('/var/www/path_to_Your_folder/media/'.$date.'/'.$id, 0777, true);
}
//Get the file
$content= file_get_contents($arr);
//Store in the filesystem.
$fp = fopen('/var/www/path_to_Your_folder/media/'.$date.'/'.$id.'/'.$file, "w");
fwrite($fp, $content);
fclose($fp)
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);
?>
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.
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.