我正试图为我的网站使用一个免费翻译服务器(这是其他人提供的),它会返回URL末尾的翻译。例如,键入此url将返回英文翻译http://www.edrdg.org/cgi-bin/wwwjdic/wwwjdic.cgi?1ZUQ%E7%BF%BB%E8%A8%B3
我的问题是,如何在不让我的网页离开我的网站的情况下,使用html/php/javascript/ajax捕获这个url的输出。
到目前为止,我已经尝试创建一个函数,它被放入我的html 的标签中
<script>
function foo()
{
var translation;
$.get('http://www.edrdg.org/cgi-bin/wwwjdic/wwwjdic.cgi?1ZUQ%E7%BF%BB%E8%A8%B3', function(data)
{
translation = data;
}
}
</script>
试着把它叫做
<div>
<p><?php echo foo(); ?></p>
</div>
对我来说,这看起来很糟糕,而且不起作用,所以我的主要问题是如何捕捉URL给我的信息,以及如何存储数据并将其显示在我的html上?谢谢
您正在尝试使用PHP中的JavaScript函数。当然,这是行不通的。JavaScript在浏览器中执行,PHP在服务器上执行。
从php中的URL获取数据的最简单方法是使用file_get_contents:
<div>
<p>
<?php
echo file_get_contents('http://www.edrdg.org/cgi-bin/wwwjdic/wwwjdic.cgi?1ZUQ%E7%BF%BB%E8%A8%B3');
?>
</p>
</div>
file_get_contents
在这种特殊情况下会很好地工作,因为页面只是文本内容,但如果您想在不使用任何换行html的情况下获取一些节点值,我会使用CURL和XPath的组合。
PHPcurl.PHP
<?php
$url = $_REQUEST['url'];
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
$html = curl_exec($curl);
curl_close($curl);
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($html);
libxml_clear_errors();
$xpath = new DOMXPath($dom);
// Find stuff
$result = $xpath->query("/html/body/pre");
$data = array();
if (!is_null($result)) {
foreach ($result as $key => $element) {
$nodes = $element->nodeValue;
$data[$key] = $nodes;
}
}
print_r($data[0]);
?>
JavaScript/jQuery
$.ajax({
url: 'curl.php',
type: 'POST',
data: {
url: 'http://www.edrdg.org/cgi-bin/wwwjdic/wwwjdic.cgi?1ZUQ%E7%BF%BB%E8%A8%B3'
},
})
.done(function (data) {
$('body').append(data);
})
.fail(function (data) {
console.log("error", data);
})