Return to Snippet

Revision: 46137
at May 13, 2011 11:47 by stewartduffy


Initial Code
<?php
/*
Template Name: Import Pods Data
*/
?>

<?php
function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}
?>

<form action="<?php echo curPageURL(); ?>" method="post">
	
	<label for="in_file">In File</label><br />
	<input type="text" name="in_file" id="in_file" /><br />
	
	<label for="use_pod">Pod to Export</label><br />
	<input type="text" name="use_pod" id="use_pod" /><br />
	
	<input type="submit" name="in_submit" />
	
</form>


<?php 
if (isset($_POST['in_submit'])) {
		
	$in_file = $_POST['in_file'];
	$use_pod = $_POST['use_pod'];
	
	import($in_file, $use_pod);
}
?>

<?php


function import($in_file, $use_pod){

	//$in_file = 'file.csv';          //This would open file.csv in the blog root.
	//$use_pod = 'newsletters';         //The name of the pod to use.
	$import = "csv";               // Can be "php" or "csv" (default: php)
	
	global $user_ID , $user_level;
	get_currentuserinfo();     //Get the information about the current user.
	if ($user_ID && (10 == $user_level)):                       //Check to see if the user is logged in and is an administrator
	  $php_data = pods_csv_import($in_file, ',', 5000);
	  $Record = new PodAPI($use_pod, 'php');
	  $Record->import($php_data);
	
	  echo "<pre>\n";
	  var_dump($php_data); 
	  echo "</pre>\n";
	  
	else: //User isn't logged in or an administrator
	  include(get_404_template());   //Nothing to see here, move along...
	  exit();                        //Exit.
	endif;
	
}




	function pods_csv_import($filename, $delimiter = ',', $max_line_len = 1000) {
		$first_row = true;
		if (false == ($handle = fopen($filename, "r"))) die("<p>Could not open $filename</p>");
		while (($data = fgetcsv($handle, $max_line_len, $delimiter)) !== FALSE) {
		  if ($first_row) {
			$field_names = $data;
			$first_row = false;
		  } else {
		  foreach ($field_names as $key => $field) {
			if ($data[$key] <> ($new_data =  preg_replace('/^array\((.*)\)$/is', '$1', $data[$key]))) {
				$new_data = explode(",",trim($new_data));
				array_walk($new_data, 'comma_trans');
	                        $data[$key] =  $new_data;
			}
			$tmp[$field] = $data[$key];
		  }
		  $out[] = $tmp;
		  }
		}
		fclose($handle);
		return $out;
	}

	function comma_trans(&$item)
	{
	    $item = strtr($item, '&#44', ','); //Translates HTML &#44; to commas
	}

?>

Initial URL


Initial Description


Initial Title
Wordpress, PODS CMS data import template

Initial Tags
php, wordpress

Initial Language
PHP