【发布时间】:2011-06-04 22:26:27
【问题描述】:
我需要将 HTML 转换为等效的 Markdown 结构文本。
OBS.:Quick and clear way of doing this with PHP & Python.
当我在 PHP 中编程时,有些人表示 Markdownify 来完成这项工作,但不幸的是,代码没有更新,实际上 它不起作用。在 sourceforge.net/projects/markdownify 有一个“注意:不支持 - 你想维护这个项目吗?联系我!Markdownify 是一个用 PHP 编写的 HTML 到 Markdown 转换器。将其视为 html2text.php 的继任者,因为它有更好的设计、更好的性能和更少的极端情况。”
据我所知,我只有两个不错的选择:
Python:Aaron Swartz 的 html2text.py
Ruby:Singpolyma 的 html2markdown.rb,基于 Nokogiri
所以,我需要从 PHP 传递 HTML 代码,调用 Ruby/Python 脚本并接收返回的输出。
(顺便说一句,有人在这里提出了类似的问题(“如何从 php 调用 ruby 脚本?”),但对我的情况没有实际信息)。
按照铁皮人的提示(如下),我得到了这个:
PHP 代码:
$t='<p><b>Hello</b><i>world!</i></p>';
$scaped=preg_quote($t,"/");
$program='python html2md.py';
//exec($program.' '.$scaped,$n); print_r($n); exit; //Works!!!
$input=$t;
$descriptorspec=array(
array('pipe','r'),//stdin is a pipe that the child will read from
array('pipe','w'),//stdout is a pipe that the child will write to
array('file','./error-output.txt','a')//stderr is a file to write to
);
$process=proc_open($program,$descriptorspec,$pipes);
if(is_resource($process)){
fwrite($pipes[0],$input);
fclose($pipes[0]);
$r=stream_get_contents($pipes[1]);
fclose($pipes[1]);
$return_value=proc_close($process);
echo "command returned $return_value\n";
print_r($pipes);
print_r($r);
}
Python 代码:
#! /usr/bin/env python
import html2text
import sys
print html2text.html2text(sys.argv[1])
#print "Hi!" #works!!!
通过以上内容,我得到了这个:
命令返回 1 大批 ( [0] => 资源 ID #17 1 => 资源 ID #18 )
并且“error-output.txt”文件说:
Traceback(最近一次调用最后一次): 文件“html2md.py”,第 5 行,在 打印 html2text.html2text(sys.argv1) IndexError: 列表索引超出范围
有什么想法吗???
Ruby 代码(仍在分析中)
#!/usr/bin/env ruby
require_relative 'html2markdown'
puts HTML2Markdown.new("<h1>#{ ARGF.read }</h1>").to_s
为了记录,我之前尝试过使用 PHP 最简单的“exec()”,但遇到了一些问题,因为 HTML 语言中一些非常常见的特殊字符。
PHP 代码:
echo exec('./hi.rb');
echo exec('./hi.py');
Ruby 代码:
#!/usr/bin/ruby
puts "Hello World!"
Python 代码:
#!usr/bin/python
import sys
print sys.argv[1]
两者都工作正常。但是当字符串有点复杂的时候:
$h='<p><b>Hello</b><i>world!</i></p>';
echo exec("python hi.py $h");
它根本不起作用。
这是因为 html 字符串需要对其特殊字符进行转义。我用这个得到它:
$t='<p><b>Hello</b><i>world!</i></p>';
$scaped=preg_quote($t,"/");
现在它就像我说的 here.
我在跑步: 软呢帽 14 红宝石 1.8.7 蟒蛇 2.7 perl 5.12.2 PHP 5.3.4 nginx 0.8.53
【问题讨论】:
-
WMD markdown editor - HTML to Markdown conversion 的可能重复项建议 Markdownify 使用 PHP 从 HTML 转换为 Markdown。
-
好吧,他们正在讨论“WMD markdown 编辑器 - HTML 到 Markdown 转换”的不同内容,尽管他们实际上正在尝试将 HTML 转换为 Markdown。另请注意,该主题仍未解决,并且没有任何好的 PHP 程序可以完成这项工作。提到了“Markdownify”,但实际上该项目是作者留下的,代码不起作用。
-
尝试在命令行上传递要更改的字符串是一个非常脆弱的解决方案,并且很容易中断。
-
如果有更好的方法使用 PHP 的“exec()”来做到这一点,那么我同意你的观点,这不是一个解决方案。
标签: php python html ruby markdown