【问题标题】:PHP code to read a web page's source and get attribute from a tag用于读取网页源并从标签获取属性的 PHP 代码
【发布时间】:2012-02-01 17:26:46
【问题描述】:

我正在阅读 PHP 页面的源代码。该页面中有一个隐藏的输入字段<input type="hidden" name="session_id" value=

$url = 'URL HERE';
$needle = '<input type="hidden" name="session_id" value=';
$contents = file_get_contents($url);
if(strpos($contents, $needle)!== false) {
echo 'found';
} else {
echo 'not found';
}

我想读取那个隐藏字段的值。

【问题讨论】:

    标签: php html dom


    【解决方案1】:

    到目前为止,最好的方法是使用 PHP 的 DOM 扩展。

    $dom = new DOMDocument;
    $dom->loadHtmlFile('your URL');
    
    $xpath = new DOMXPath($dom);
    
    $elements = $xpath->query('//input[@name="session_id"]');
    if ($elements->length) {
        echo "found: ", $elements->item(0)->getAttribute('value');
    } else {
        echo "not found";
    }
    

    【讨论】:

    • +1 刚刚删除了我自己的答案以支持 xpath 解决方案:-)
    • @imi 这不是一个有效的 HTML 文档。您需要使用我描述的相同技术来抑制警告in this answer
    • 找不到输入[@name="session_id"]
    • @imi 你确定它存在吗?
    【解决方案2】:

    我会研究 PHP 的原生 DOMDocument 扩展:

    http://www.php.net/manual/en/domdocument.getelementbyid.php#example-4867

    【讨论】:

    • 身份证?这是否适用于 DOMDocument 中的 name 属性?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    相关资源
    最近更新 更多