簡體   English   中英

在HTML文件中查找並保存href鏈接,並在PHP中替換為id

[英]Find and save href links in a html file and replace by id in PHP

我有新聞通訊的html文件。 我需要捕獲html文件中的href鏈接並將其保存在表中。 並用新的跟蹤鏈接和ID替換鏈接。 我能夠找到鏈接,並通過以下PHP插入到數據庫

<?PHP
$con=mysqli_connect("localhost","root","","test");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }


$html = file_get_contents('test.html');

$dom = new DOMDocument();
@$dom->loadHTML($html);


$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");

for ($i = 0; $i < $hrefs->length; $i++) {
       $href = $hrefs->item($i);
       $url = $href->getAttribute('href');
       mysqli_query($con,"INSERT INTO urls (id, url)
VALUES ('','$url')");
       echo $url.'<br />';
}
?>

id是主鍵和auto_increment。 現在,我需要用存儲的行ID替換html文件中的那些鏈接。 因此,新的網址應類似於“ http://www.mysite.com/track.php?id=1 ”。 最后,我需要使用更新的鏈接生成一個新的html文件。 請幫我

嗨,我放

$href = 'http://mysite.com/track.php?id=' . mysqli_insert_id($con);
$dom->saveHTMLFile("temp".$y.".html");

插入表后。 但是我沒有在生成的html文件中替換鏈接,請幫助

希望我能正確理解您的問題。 最好使用preg_replace()替換ID。 $newUrl = preg_replace('/[0-9]*$/', mysqli_insert_id($con), $url); 將其放在mysqli_query

該preg_replace中的正則表達式的目標是$ url末尾的數字。 我希望這就是你要的。

一旦有了新的URL,就可以使用它設置href屬性,然后使用$dom->saveHtml();獲得新的html的輸出$dom->saveHtml(); 使用file_put_contents()或您喜歡的任何方法將其file_put_contents()一些新文件。

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM