Home > Article > Backend Development > PHP script to implement Markdown articles uploaded to Qiniu Image Bed
After using Markdown to write articles, we often need to publish them to different platforms. Here we will encounter a problem. The pictures of the article need to be uploaded manually, which is very inconvenient to manage. Therefore, it is strongly recommended to upload the pictures to the picture. In this way, an article can be easily synchronized to major platforms. Next, use PHP to implement this function, select Qiniu Cloud as the image bed
Create and enter the project
$ mkdir markdown-images-to-qiniu $ cd markdown-images-to-qiniu
Install Qiniu official extension
$ composer require qiniu/php-sdk
The implementation idea is very simple
● Read the makrdown file
● Regularly match all the pictures
● Upload the pictures in sequence
● Replace the address of the article picture with the image bed Address
● Save the replaced article
The following is the specific implementation. First, create the script index.php in the project directory,
<?php require 'vendor/autoload.php'; use Qiniu\Auth; use Qiniu\Storage\UploadManager; // 1. 读取 `makrdown` 文件 $file = $argv[1]; if(! file_exists($file) ){ return "找不到文件{$file}"; } $orginalContent = file_get_contents($file); // 2. 正则匹配出所有的图片 preg_match_all( '/\!\[.*\]\(.+\)/', $orginalContent, $matches, PREG_PATTERN_ORDER ); $mdImageArr = $matches[0]; if(! count($mdImageArr) ){ return "无需上传图片"; } // 3. 依次上传图片 $accessKey = '你的 AccessKey'; $secretKey = '你的 SecretKey'; $bucket = '你的七牛空间名'; // eg. mindgeek $url = "空间所绑定的域名"; // eg. http://qiniu.site.com $auth = new Auth($accessKey, $secretKey); $token = $auth->uploadToken($bucket); $uploadMgr = new UploadManager(); $content = $orginalContent; foreach ($mdImageArr as $image) { $start = mb_strpos($image, '](') + 2; $localPath = mb_substr($image, $start, -1); $extension = pathinfo($localPath)['extension']; $uploadPath = uniqid(). ".". $extension; list($ret, $error) = $uploadMgr->putFile($token, $uploadPath, $localPath); if(! $error ){ // 4. 将文章图片的地址替换为图床地址 $content = str_replace($localPath, $url.$uploadPath, $content); echo "{$uploadPath} 上传成功。\n"; } else { echo "{$uploadPath} 上传失败。\n"; } } // 5. 保存替换后的文章 file_put_contents($file, $content);
Use
$ php index.php test.md
The above is the detailed content of PHP script to implement Markdown articles uploaded to Qiniu Image Bed. For more information, please follow other related articles on the PHP Chinese website!