html 导入CSV文件并将其另存为新帖子

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html 导入CSV文件并将其另存为新帖子相关的知识,希望对你有一定的参考价值。

<?php

/** Setup WordPress */
require_once($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php');

/** Set file path */
$file = $_SERVER['DOCUMENT_ROOT'] . '/wp-content/themes/liquid/import.csv';

/** Remove existing files */
if (file_exists($file)) {
  unlink($file);
}

/** Move the uploaded file to the $file path */
move_uploaded_file($_FILES['import']['tmp_name'], $file);

/**
 * Convert a comma separated file into an object.
 * The first row should contain the array keys.
 */
function csv_to_array($filename='', $delimiter=',')
{
	if(!file_exists($filename) || !is_readable($filename))
		return FALSE;

	$header = NULL;
	$data = array();
	if (($handle = fopen($filename, 'r')) !== FALSE)
	{
		while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
		{
			if(!$header)
				$header = $row;
			else
				$data[] = array_combine($header, $row);
		}
		fclose($handle);
	}

  $object = json_decode(json_encode($data), FALSE);

  return $object;
}

/**
 * Take imported data and insert it into the database
 * Delete the import file after it's been imported
 */
if (file_exists($file)) {

  $array = csv_to_array($file);

  foreach($array as $item) {
    $user_id = get_current_user_id();

    /**
     * Setup Post Data here to be inserted into the database
     * include post type and meta values (Advanced Custom Fields)
     */
    $post_data = [
      'post_author'  => $user_id,
      'post_content' => '',
      'post_title'   => $item->csv_column_name,
      'post_status'  => 'publish',
      'post_type'    => 'your_post_type',
      'meta_input'   => [
        'custom_field_name' => $item->csv_column_name,
      ]
    ];

    wp_insert_post($post_data);
  }

  unlink($file);

  echo "CSV Data was imported! :)";
} else {
  echo "Something went wrong...";
}
<div class="row">
  <div class="column">
    <form class="" action="/wp-content/themes/liquid/import.php" method="post" enctype="multipart/form-data">
      <input type="file" name="import" value="Upload JSON">
      <button type="submit" class="button">Upload</button>
    </form>
  </div>
</div>

以上是关于html 导入CSV文件并将其另存为新帖子的主要内容,如果未能解决你的问题,请参考以下文章

html 导入JSON文件并将其另存为新帖子

下载 aspx 页面并将其另存为 HTML 页面 [关闭]

Python:如何打开多页 .xlsx 文件(带格式)并编辑一些单元格并将其另存为另一个 .xlsx 文件

为数据帧分配新名称并将其另存为R中的单独对象

Applescript Excel 2016 另存为 CSV

遍历下拉列表并将工作簿另存为新文件