0

我正在尝试通过以下方式对维基百科进行 API 调用:http ://en.wikipedia.org/w/api.php?action=parse&page=Petunia&format= xml,但 xml 中充满了 html 和 css 标签。

有没有办法只获取没有标签的纯文本?谢谢!

*编辑1:

$json = json_decode(file_get_contents('http://en.wikipedia.org/w/api.php?action=parse&page=Petunia&format=json'));
$txt  = strip_tags($json->text);
var_dump($json);

显示为空。

4

2 回答 2

1

问题在这里得到了部分回答

$url = 'http://en.wikipedia.org/w/api.php?action=parse&page=Petunia&format=json&prop=text';
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_USERAGENT, "TestScript"); // required by wikipedia.org server
$c = curl_exec($ch);

$json = json_decode($c);

var_dump(strip_tags($json->{'parse'}->{'text'}->{'*'}))

我无法使用file_get_contents,但它适用于cURL.

于 2012-01-11T04:44:35.077 回答
0

可以使用 xml 从 wikipedia 获取信息或描述。

       $url = "http://en.wikipedia.org/w/api.php?action=opensearch&search=".$term."&format=xml&limit=1";
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HTTPGET, TRUE);
        curl_setopt($ch, CURLOPT_POST, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, false); // 根据需要包含头部
        curl_setopt($ch, CURLOPT_NOBODY, FALSE); // 返回正文
        curl_setopt($ch, CURLOPT_VERBOSE, FALSE); // 最小化日志
        curl_setopt($ch, CURLOPT_REFERER, ""); // 引用值
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 没有证书
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); // 跟随重定向
        curl_setopt($ch, CURLOPT_MAXREDIRS, 4); // 将重定向限制为四个
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // 以字符串形式返回
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; he; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8"); // 网络机器人名称
        $page = curl_exec($ch);
        $xml = simplexml_load_string($page);
        if((string)$xml->Section->Item->Description) {
            print_r(array((string)$xml->Section->Item->Text,
            (string)$xml->Section->Item->Description,
            (string)$xml->Section->Item->Url));
        } 别的 {
            回声“对不起”;
        }

但是 curl 必须安装在服务器上...祝您有美好的一天...

于 2012-08-15T08:03:33.817 回答