我正在尝试通过以下方式对维基百科进行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);
显示空。
答案 0 :(得分:1)
问题已部分回答here
$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
一起使用。
答案 1 :(得分:0)
可以使用xml从维基百科中获取信息或描述。
$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); // Include head as needed curl_setopt($ch, CURLOPT_NOBODY, FALSE); // Return body curl_setopt($ch, CURLOPT_VERBOSE, FALSE); // Minimize logs curl_setopt($ch, CURLOPT_REFERER, ""); // Referer value curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // No certificate curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); // Follow redirects curl_setopt($ch, CURLOPT_MAXREDIRS, 4); // Limit redirections to four curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // Return in string 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"); // Webbot name $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)); } else { echo "sorry"; }
但是curl必须安装在服务器上......祝你有个美好的一天......