![](/img/trans.png)
[英]PHP: How to find an element with particular name attribute in html (from url)
[英]How to use php to retrieve the particular element and attribute from a remote HTML page?
如何使用 php 從遠程 HTML 頁面檢索特定元素和屬性?
例如,如果要檢索的元素和屬性具有以下格式:
<a href="/dir/someid/" class="ccc">
任何幫助將不勝感激。
將使用的代碼方法:
<?php
$file = fopen ("http://www.example.com/", "r");
if (!$file) {
echo "<p>Unable to open remote file.\n";
exit;
}
while (!feof ($file)) {
$line = fgets ($file, 1024);
/* This only works if the title and its tags are on one line */
if (preg_match ("@\<title\>(.*)\</title\>@i", $line, $out)) {
$title = $out[1];
break;
}
}
fclose($file);
?>
解決方案:
$homepage = file_get_contents ("https://www.somedomain.com");
$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;
@$doc->loadHTML($homepage);
$xpath = new DOMXpath($doc);
$results = $xpath->query("//div[@class='some-class']");
foreach($results as $contextNode) {
$text = $xpath->evaluate("string(./a[1])",$contextNode);
$href = $xpath->evaluate("string(./a[1]/@href)",$contextNode);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.