通过选择标记名称在PHP中创建属性

时间:2017-12-22 00:15:09

标签: php html attributes element

我正在尝试加载html,找到一个标签并在显示它之前添加一个属性。

我试过了:

libxml_use_internal_errors(true);

$domDocument->loadHTML("<html><body>Test<br></body></html>");
$domElement = $domDocument->getElementsByTagName('body');

foreach ($domElement as $formula) {
    $formula->nodeValue->createAttribute('name')->value = 'attributevalue';
}

libxml_use_internal_errors(false);

但我有这个错误:

  

在字符串

上调用成员函数createAttribute()

你有解决方案吗?

祝你好运

3 个答案:

答案 0 :(得分:1)

nodeValue返回String类型,这不是创建属性的方式。

事实上,节点的类型是DOMElement,因此您需要将该属性设置为与以下代码类似:

<?php
$domDocument = new DOMDocument();
$domDocument->loadHTML("<html><body>Test<br></body></html>");
$domElement = $domDocument->getElementsByTagName('body');
foreach ($domElement as $formula) {
    $formula->setAttribute("name", "attributevalue");
}
?>

答案 1 :(得分:1)

这是一个可能的解决方案,其中使用setAttribute而不是创建。虽然我不确定循环的目的,因为通常只有1个body标签。

libxml_use_internal_errors(true);

$domDocument->loadHTML("<html><body>Test<br></body></html>");
$domElement = $domDocument->getElementsByTagName('body');

foreach ($domElement as $formula) {
    $formula->setAttribute('name', 'thevalue');
}

libxml_use_internal_errors(false);

答案 2 :(得分:0)

尝试这样

libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTML("<html><body>Test<br></body></html>");
$domElements = $doc->getElementsByTagName('body');
foreach ($domElements as $domElement) {
    $domAttribute = $doc->createAttribute('name');
    $domAttribute->value = 'attributevalue';
    $domElement->appendChild($domAttribute);
    print_r($domElement->getAttribute('name'));
    // returns attributevalue
}
libxml_use_internal_errors(false);

尝试@PHP-Sandbox