Copie de Tumblr sur Shaarli
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

109 lines
2.0KB

  1. #!/usr/bin/env php
  2. <?php
  3. requireAutoloader();
  4. ini_set('display_errors', 'stderr');
  5. foreach ($argv as $i => $arg) {
  6. if ($i === 0) {
  7. continue;
  8. }
  9. if (substr($arg, 0, 1) === '-') {
  10. switch ($arg) {
  11. case '-h':
  12. case '--help':
  13. echo getHelpText();
  14. exit(0);
  15. default:
  16. fail('Unknown option: ' . $arg);
  17. }
  18. } else {
  19. $src = $argv[1];
  20. }
  21. }
  22. if (isset($src)) {
  23. if (!file_exists($src)) {
  24. fail('File not found: ' . $src);
  25. }
  26. $html = file_get_contents($src);
  27. } else {
  28. $stdin = fopen('php://stdin', 'r');
  29. stream_set_blocking($stdin, false);
  30. $html = stream_get_contents($stdin);
  31. fclose($stdin);
  32. if (empty($html)) {
  33. fail(getHelpText());
  34. }
  35. }
  36. $converter = new League\HTMLToMarkdown\HtmlConverter();
  37. echo $converter->convert($html);
  38. /**
  39. * Get help and usage info
  40. *
  41. * @return string
  42. */
  43. function getHelpText()
  44. {
  45. return <<<HELP
  46. HTML To Markdown
  47. Usage: html-to-markdown [OPTIONS] [FILE]
  48. -h, --help Shows help and usage information
  49. If no file is given, input will be read from STDIN
  50. Examples:
  51. Converting a file named document.html:
  52. html-to-markdown document.html
  53. Converting a file and saving its output:
  54. html-to-markdown document.html > output.md
  55. Converting from STDIN:
  56. echo -e '<h1>Hello World!</h1>' | html-to-markdown
  57. Converting from STDIN and saving the output:
  58. echo -e '<h1>Hello World!</h1>' | html-to-markdown > output.md
  59. HELP;
  60. }
  61. /**
  62. * @param string $message Error message
  63. */
  64. function fail($message)
  65. {
  66. fwrite(STDERR, $message . "\n");
  67. exit(1);
  68. }
  69. function requireAutoloader()
  70. {
  71. $autoloadPaths = array(
  72. // Local package usage
  73. __DIR__ . '/../vendor/autoload.php',
  74. // Package was included as a library
  75. __DIR__ . '/../../../autoload.php',
  76. );
  77. foreach ($autoloadPaths as $path) {
  78. if (file_exists($path)) {
  79. require_once $path;
  80. break;
  81. }
  82. }
  83. }