简体   繁体   English

使用PHP获取页面的源代码,使用JavaScript进行操作

[英]Get a page's source with PHP, manipulate with JavaScript

JavaScript cannot get an arbitrary page's source code, last I knew. 我最后知道,JavaScript无法获取任意页面的源代码。 But PHP can pretty easliy. 但是PHP可以很容易地实现。

//get page source code with php
<?php

url = 'http://www.thesaurus.com/browse/strong?s=t';
$src = file_get_contents($url);

?>

PHP is not good at manipulating the DOM, but jQuery is great for that! PHP不擅长操纵DOM,但是jQuery非常适合!

I would like to do something like 我想做类似的事情

//manipulate source code with javascript
<script>
html = '"' + <?php echo $src;?> + '"';
listItems = $(html + " li");
printLists = '';
$.each(listItems, function(ind, el) {
    printLists += el.innerHTML + "<br/>";
});

document.write(printLists);

</script>

But, any time I echo $src into the script tag, it gets interpreted as HTML immediately and the page becomes a live mockery of the actual site. 但是,每当我在脚本标签中回显$src ,它都会立即被解释为HTML,并且该页面成为实际站点的实时嘲讽。

//Actually just shows me thesaurus.com@strong
<body>
    <div id="holder" style="display: none;"></div>

<script>
    holder = $("#holder");
    nodeNames = [];
    html = $.parseHTML(<?php echo $src;?>, holder, false);
</script>
</body>

The phrase 'virtual DOM' sounds right, though I really don't want any of the copied source code to show up at all. “虚拟DOM”一词听起来不错,尽管我真的不希望出现任何复制的源代码。 I just want to extract certain parts of it : to run a script from the console, search a few thesaurus sites for a term, take the results, and save them to JSON accessed by a local thesaurus script. 我只想提取其中的某些部分:从控制台运行脚本,在几个词库站点中搜索术语,获取结果,然后将其保存到本地词库脚本访问的JSON中。

I have a solid idea of how to do everything else, didn't expect this to be the tricky part! 我对如何做其他事情有一个扎实的想法,没想到这是棘手的部分!

Any suggestions on preventing the browser from parsing HTML? 关于防止浏览器解析HTML有什么建议吗?

(I would prefer this to run just as a script file without a browser anyway, but had trouble loading jQuery in a thesaurus.js file.) (我希望它可以像脚本文件一样在没有浏览器的情况下运行,但是在thesaurus.js文件中加载jQuery时遇到了麻烦。)

You could run a php script to get file contents and echo the results to a textarea with readonly/disabled on, then query that php file through ajax to display the resulting textarea on the page. 您可以运行php脚本来获取文件内容,并将结果回显到具有只读/禁用状态的textarea,然后通过ajax查询该php文件,以在页面上显示结果textarea。

For example, output.php: 例如,output.php:

<?php
    $str = '<p>I am a paragraph.</p>';
    echo '<textarea readonly="readonly">'.$str.'</textarea>';
?>

AJAX call in the original file: 原始文件中的AJAX调用:

$.ajax({url: 'output.php', success: function(data) { $('#result').html(data); }});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM