2012-09-22 14 views
1

我需要一种方法来获取具有特定ID的元素并使用PHP显示它。我是一个PHP noob,所以到目前为止这是非常困难的。所有其他类似的问题都有点复杂,所以我想知道是否有人可以向我解释。使用PHP获取网页的一部分

为了更具体地说明我想要什么,我正在为一个minecraft服务器进行拼写搜索。我们的网站是http://pvpzone.org/,wiki是http://pvpzone.wikispaces.com/。每个咒语在wiki上都有一个页面,就像pvpzone.wikispaces.com/Vanish中的“消失”一样。法术搜索的想法是寻找咒语的一种更简单的方法,您输入咒语名称并获得结果。 div'wiki wikiPage'中包含拼写数据。我想得到那个div并显示它。可悲的是我无法连接到任何形式的数据库,它是由Wikispaces托管的,他们不允许这样做。

我希望这已经很清楚,如果你愿意,可以问我更多的细节。以下是我迄今为止:

<?php 
if(isset($_POST['submit'])) 
{ 
    $spell=$_POST['spell']; 
    $pvpwiki="http://pvpzone.wikispaces.com/"; 
    $site=$pvpwiki . $spell; 
    $submit=true; 
} 
?> 
<!DOCTYPE html> 
<html lang="en"> 
    <head> 
     <meta http-equiv="content-type" content="text/html; charset=utf-8"> 
     <title>Spell search</title> 
    </head> 
    <body> 
     <form name="spellsearch" id="spellsearchform" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> 
      <input type="text" name="spell" value="<?php if(!isset($_POST['submit'])){echo("Vanish");}?>"></input> 
      <input type="submit" value="Search" name="submit"></input> 
     </form> 
      <?php 
       $doc = new DomDocument; 
       $doc->validateOnParse = true; 
       $doc->loadHtml(file_get_contents($site)); 
       var_dump($doc->getElementById('wiki wikiPage')); 

       if($doc == false && $submit) 
       { 
        echo("<br />" . "That is not a spell!"); 
       } 
      ?> 
    </body> 
</html> 

我的问题,现在是我得到一个语法错误(警告:DOM文档:: loadHTML()[domdocument.loadhtml]:在实体已经定义ID target_editor,行: 212 in /home/content/d/e/x/dext0459/html/russellsayshi/phpspellsearch.php on line 24 NULL),我真的很感激你的帮忙。

+3

参见:http://stackoverflow.com/a/3614620/1329367 – Mahn

+0

@马恩:好的提示,但事实证明,这不是问题。无论如何,如果*是*的问题,你可以得到具有重复'id'属性值与xpath的元素。 – hakre

回答

1

你看到错误信息只是一个警告:

警告:DOM文档:: loadHTML()[domdocument.loadhtml]:在实体,线已经定义ID target_editor:212在/ home /内容/ d/e/x/dext0459/html/russellsayshi/phpspellsearch.php 24行无效

您可以忽略这些,它们不会阻止您。如果你在你的网站上看到它们,你没有正确配置它,你应该记录错误,而不是显示它们。

反正在这种情况下,该库可以禁用它们这样,太:加载HTML之前

libxml_use_internal_errors(true); 

调用它。该HTML顺便说一句。当我尝试使用该网站时没有导致错误。

下一个错误是,你正在寻找一个类不是一个ID。查找ID改为:

$div = $doc->getElementById('content_view'); 

整个代码示例:

function get_wiki_page_div($page) 
{ 
    $url = sprintf('http://pvpzone.wikispaces.com/%s', urlencode($page)); 

    $doc = new DOMDocument(); 
    $doc->validateOnParse = true; 
    libxml_use_internal_errors(true); 

    $doc->loadHTMLFile($url); 

    $div = $doc->getElementById('content_view'); 

    if (!$div) { 
     return false; 
    } 

    return $doc->saveXML($div); 
} 

用法:

<?php 
$submit = isset($_POST['submit']); 
if ($submit) 
{ 
    $spell = $_POST['spell']; 
    $result = get_wiki_page_div($spell); 
} 
?> 

... 


<?php 
if ($submit) 
{ 
    echo $result ? $result : '<div>This is not a Spell!</div>'; 
} 
?> 
+0

非常感谢你,你是一个救星!这工作很好,真的很感激它。 – russellsayshi

+0

从未想过我会看到@hakra暗示忽略警告。但是我认为在这种情况下它是可以接受的,只是DOMDocument很奇怪。一个人想知道为什么DOMDocument首先显示警告...... – Mahn