2024 年日本 PHP 研討會

DOMElement::removeAttribute

(PHP 5, PHP 7, PHP 8)

DOMElement::removeAttribute移除屬性

說明

public DOMElement::removeAttribute(字串 $qualifiedName): 布林值

從元素中移除名為 qualifiedName 的屬性。

參數

qualifiedName

屬性名稱。

回傳值

成功時回傳 true,失敗時回傳 false

錯誤/例外

DOM_NO_MODIFICATION_ALLOWED_ERR

如果節點是唯讀的,則會拋出此例外。

另請參閱

新增註解

使用者貢獻的註解 2 則註解

Rakesh Verma - rakeshnsony at gmail dot com
14 年前
<?php

//將您的 HTML 儲存到 $html 變數中。

$html="<html>
<head>
<title>Rakesh Verma</title>
</head>

<body>
<a href='http://example.com'>Example</a>
<a href='http://google.com'>Google</a>
<a href='http://www.yahoo.com'>Yahoo</a>
</body>

</html>"
;

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

//評估 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');

//移除並設定 target 屬性
$href->removeAttribute('target');
$href->setAttribute("target", "_blank");

$newURL=$url.".au";

//移除並設定 href 屬性
$href->removeAttribute('href');
$href->setAttribute("href", $newURL);
}

//儲存 html
$html=$dom->saveHTML();

echo
$html;

?>
suwayan at mail dot ru
12 年前
<?php
/*當我嘗試從未驗證的 HTML 或 XML 文件中獲取某些屬性時,PHP 會中止執行,且日誌或輸出中沒有任何錯誤訊息:
*/
function is_attribute_value($obj,$type,$value)
{
$_ret=false;
if(
$obj)
{
if(
$val=$obj->getAttribute($type))
{
if(
$val==$value)
{
$_ret=true;
}
}
}
return
$_ret;
}
//這個檢查對我有幫助:
function is_attribute_value($obj,$type,$value)
{
$_ret=false;
if(
$obj->attributes)
{
if(
$val=$obj->getAttribute($type))
{
if(
$val==$value)
{
$_ret=true;
}
}
}
return
$_ret;
}
?>
To Top