LoginSignup
1
2

More than 5 years have passed since last update.

PHPでWGETを実装する

Last updated at Posted at 2018-08-12

こんにちは
私はバッチはPHPでアプリはPythonで実装しています。

今回は私がよく使う[ファイル名.php]で[ファイル名.json]としてワードプレスの更新記事を取得する方法を解説します。

まずフォルダが書き込み可能となっているかどうかを確認してください。
もし書き込み可能となっているか不安な場合は以下のコマンドを入力してファイル書き込み可能としてください

$ sudo chmod -R 755 <使用するフォルダ名>

PHPでネットワークからファイルを取得するためにはCURLライブラリが必要です。
これは初めからPHPに入っているので気にしなくて大丈夫です。

それではスクリプトを見てみましょう。

今回は私が管理している
https://根岸康雄.yokohama

からJSONのデータを取得します
以下が取得するためのスクリプトです(くれぐれもガンガンやらないように!XSERVERの通常のプランなので重くなってしまいます)

wget.php

<?php
 # setup a global file pointer
$GlobalFileHandle = null;

function saveRemoteFile($url, $filename) {

  global $GlobalFileHandle;

  set_time_limit(0);

  # Open the file for writing...
  $GlobalFileHandle = fopen($filename, 'w+');

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_FILE, $GlobalFileHandle);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_USERAGENT, "MY+USER+AGENT"); //Make this valid if possible
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); # optional
  curl_setopt($ch, CURLOPT_TIMEOUT, -1); # optional: -1 = unlimited, 3600 = 1 hour
  curl_setopt($ch, CURLOPT_VERBOSE, false); # Set to true to see all the innards

  # Only if you need to bypass SSL certificate validation
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

  # Assign a callback function to the CURL Write-Function
  curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'curlWriteFile');

  # Exceute the download - note we DO NOT put the result into a variable!
  curl_exec($ch);

  # Close CURL
  curl_close($ch);

  # Close the file pointer
  fclose($GlobalFileHandle);
}

function curlWriteFile($cp, $data) {
  global $GlobalFileHandle;
  $len = fwrite($GlobalFileHandle, $data);
  return $len;
}
$url = 'https://xn--sjt69bu2p1r2c.yokohama//wp-json/wp/v2/posts?per_page=100';
$filename ='./'. explode('.',basename(__FILE__))[0].'.json';;
saveRemoteFile($url,$filename);

 ?>

そうすれば同じディレクトリに”wget.json”というファイルが作成されていると思います。
$urlの部分を変えたりユーザーに入力を要求するようにすればおもしろいと思います。

AjaxなどでCORSという問題があります。

CORSとは

要はリモートからのファイルをブラウザから直接取得できない、そこでこういったPHPのCURLのスクリプトを使用してあらかじめリモートのサーバーからダウンロードしておくと良いでしょう。

私の個人ブログでも解説しているのでご覧ください!

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2