首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP来获取当前页面的特定内容

PHP来获取当前页面的特定内容
EN

Stack Overflow用户
提问于 2012-11-07 02:33:03
回答 2查看 4.4K关注 0票数 0

我正在尝试找出是否可能&使用什么代码:加载当前页面的内容,并使用PHP或PHP Simple Html DOM Parser.回显特定页面(c.html)的相对路径,该路径位于"#navbar a“中

到目前为止我的代码如下:

代码语言:javascript
复制
<?php
$pg = 'c.html';
include_once '%resource(simple_html_dom.php)%';
/* $cpath = $_SERVER['REQUEST_URI']; Old version */  // Path to current pg from root
$cpath = "http://www.".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
echo var_dump($cpath).": Current Root Path"."<br />";  // "http://www.partiproductions.com/copyr/index.php" - Correct
$cfile = basename($cpath);
echo 'Current File: ' . $cfile . "<br />"; // "index.php" - Current pg, Correct

$html = file_get_html($cpath); // Getting Warning: URL file-access is disabled in the server configuration & failed to open stream: no suitable wrapper could be found in.. & Fatal error: Call to a member function find() on a non-object in...
foreach($html->find(sprintf('#navbar a[href=%s]', $pg)) as $path) {
  echo 'Path: ' . $path."<br />";
}
?>
EN

回答 2

Stack Overflow用户

发布于 2012-11-07 03:11:15

您遇到的主要问题是对file_get_html($cfile)的调用。

示例中的$cfile将包含类似于/copyr/index.php的内容

当您将其传递给file_get_html()时,它将在服务器的根目录中查找一个目录/copyr,并在该目录中查找一个index.php文件。根据您已经指出的警告,您实际上在服务器的根目录下并没有这个文件夹结构。

您实际需要做的是在当前拥有的URI前面包含完整的URL,如下所示:

代码语言:javascript
复制
$cpath = "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];

这将产生如下路径:http://www.yourserver.com/copyr/index.php,然后您应该为file_get_html()工作;

票数 1
EN

Stack Overflow用户

发布于 2012-11-10 02:13:01

基于来自发问者的更新信息,我将采用不同的方法。

创建一个仅包含您希望在两个文件之间共享的内容的新文件。然后,在这两个文件中(如果需要,稍后在更多文件中)使用include()函数注入来自新共享内容文件的内容。

index.php文件:

代码语言:javascript
复制
<?php
//Any require PHP code goes here
?>
<html>
    <body>
    <?php include('sharedfile.php');?>
    </body>
</html>

/copyr/c.php文件:

代码语言:javascript
复制
<?php
//Any require PHP code goes here
?>
<html>
    <body>
    <?php include('../sharedfile.php');?>
    </body>
</html>

sharedfile.php:

代码语言:javascript
复制
// You need to close the PHP tag before echoing HTML content
?>
<p>
    This content is displayed via include() both on index.php and /copyr/c.php
</p>
<?php  // The PHP tag needs to be re-opened at the end of your shared file

这里的好处是,您现在可以通过遵循相同的技术在整个站点中使用任何文件中的sharedfile.php文件内容。您也不需要解析页面的DOM来剥离希望跨多个页面显示的内容,这可能会很慢且容易出错。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13257146

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档