php domdocument getelementbyid,PHP DOMDocument getElementById()用法及代码示例

DOMDocument::getElementById()函数是PHP中的内置函数,用于搜索具有特定ID的元素。

用法:

DOMElement DOMDocument::getElementById( string $elementId )

参数:此函数接受单个参数$elementId,该参数包含要搜索的id。

返回值:如果找不到该元素,则此函数返回DOMElement或NULL。

下面给出的程序说明了PHP中的DOMDocument::getElementById()函数:

程序1:在此程序中,我们将获得具有特定ID的元素的标记名。

// Create a new DOM Document

$dom = new DOMDocument('1.0', 'iso-8859-1');

// Enable validate on parse

$dom->validateOnParse = true;

// Create a div element

$element = $dom->appendChild(new DOMElement('div'));

// Create a id attribute to div

$attr = $element->setAttributeNode(

new DOMAttr('id', 'my_id'));

// Set that attribute as id

$element->setIDAttribute('id', true);

// Get the tag name

$tagname = $dom->getElementById('my_id')->tagName;

echo $tagname;

?>

输出:

div // Because id 'my_id' is applied to div tag.

程序2:在此程序中,我们将获取具有特定ID的元素的内容。

// Create a new DOM Document

$dom = new DOMDocument('1.0', 'iso-8859-1');

// Enable validate on parse

$dom->validateOnParse = true;

// Create a div element

$element = $dom->appendChild(new DOMElement('div',

'Hey, this is the text content of the div element.'));

// Create a id attribute to div

$attr = $element->setAttributeNode(

new DOMAttr('id', 'my_id'));

// Set that attribute as id

$element->setIDAttribute('id', true);

// Get the tag content

$tagcontent = $dom->getElementById('my_id')->textContent;

echo $tagcontent;

?>

输出:

Hey, this is the text content of the div element.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值