【问题标题】:Use PHP to get tags within a set tag id, class or other from a Website使用 PHP 从网站中获取一组标签 id、类或其他标签中的标签
【发布时间】:2014-08-16 00:27:10
【问题描述】:

我被困住了。我正在尝试从远程网站提取预定义标签内的所有 html 标签、它们的属性和文本内容。

示例: <div id="its attributes">its text content</div>

我可以通过使用 php 的 DOMDocument 类来提取任何标签,使用它们的 id 或类,我只是无法告诉 php 限制返回到该预定义标签。

示例: <div id="predefined">... return all this ...</div>

我没有任何代码示例,因为我尝试了无数搜索中的许多选项,但都返回了错误的结果。

你能帮忙吗?

更新:我在这里找到了答案: PHP function to grab all links inside a <DIV> on remote site using scrape method

感谢所有帮助。

【问题讨论】:

  • 您需要使用 PHP 还是可以使用 JavaScript(使用 jQuery)?
  • 说实话,我没有考虑过 Javascript 或 jQuery。但是,最好使用 Php,因为我正在编写代码以将这些标签提取到 mysql 表中。
  • 好吧,我认为你应该认真看看它(两者)。您的问题通常使用 jQuery 很容易解决,当您了解基本知识时,您甚至不再需要帮助来实现您想要的目标
  • 谢谢 Oliboy50,我会调查的。所有建议都有帮助。我应该补充一点,我正在尝试从远程网站获取这些标签。是否仍然可以使用 jQuery/Javascript?

标签: php html parsing tags domdocument


【解决方案1】:

您可以使用getElementById,然后访问nodeValue

$doc->loadHTML('<html><body><div id="predefined">... return all this ...</div></body></html>');
$i = $doc->getElementById('predefined');
echo $i->nodeValue;

【讨论】:

    【解决方案2】:

    如果你想学习 JavaScript 和 jQuery:

    假设这个 HTML :

    <div id="predefined">... return all this ...</div>
    

    使用这段 JavaScript 代码(使用 jQuery)(我试图让它变得简单,但如果你学得好,你会做得更好):

    // To get the content from a single HTML tag
    var theID = "predefined";
    var theContent = $("#" + theID).text(); // Or .html() if you want the whole content
    
    // To POST the extracted content to your PHP page in order to write to your mySQL db
    $.ajax({
        type: "POST",
        url: "http://www.myapp.com/mypage.php",
        data: { id: theID, content: theContent },
        success: function(response){ // just in case you need a response from your PHP stuff
            alert(response);
        }
    });
    

    然后在你的 PHP "http://www.myapp.com/mypage.php" 中:

    <?php
        $id = $_POST["id"];
        $content = $_POST["content"];
    
        // Note: Always sanitize posted data, to prevent injections and other malicious code.
    
        // Here you can save the data to your MySQL db
    
        echo "it worked!"; // This is the response that your "success" function will get in your Javascript code
    ?>
    

    好吧,我不确定这是针对您的特殊情况的最佳答案,但无论如何您真的应该学习 JavaScript =)

    【讨论】:

      猜你喜欢
      • 2019-11-02
      • 2018-09-11
      • 1970-01-01
      • 1970-01-01
      • 2015-01-27
      • 2022-09-23
      • 2023-03-27
      • 1970-01-01
      • 2021-05-13
      相关资源
      最近更新 更多