如何使用对象作为 PHP 的 createElement 的参数
我正在使用变量来创建元素。但我收到这个错误:
警告:DOMDocument::createElement() 期望参数 1 为字符串,给定对象
// load up your XML
$xml = new DOMDocument;
$xml->load('test.xml');
$parent_node = $xml->createElement('parent');
foreach ($xml->getElementsByTagName('product') as $product )
{
$append = array();
foreach($product->getElementsByTagName('name') as $name ) {
// Stick $name onto the array
$append[] = $name;
}
foreach ($append as $a) {
$parent_node->appendChild($xml->createElement($a, 'anothervalue'));
$product->appendChild($parent_node);
}
$product->removeChild($xml->getElementsByTagName('details')->item(0));
//$product->appendChild($element);
}
// final result:
$result = $xml->saveXML();
原始 XML 结构的对象:
<products>
<product>
<name>text</name>
<name>text</name>
<name>text</name>
</product>
</products>
我正在尝试创建一个新元素,其值是其自身的文本。我知道它看起来是什么样子。为什么我不能使用对象来创建元素?
我试图获得的结果将如下所示:
<products>
<product>
<text>text</text>
<text>text</text>
<text>text</text>
</product>
</products>
I'm using a variable to create an element. But I'm getting this error:
Warning: DOMDocument::createElement() expects parameter 1 to be string, object given
// load up your XML
$xml = new DOMDocument;
$xml->load('test.xml');
$parent_node = $xml->createElement('parent');
foreach ($xml->getElementsByTagName('product') as $product )
{
$append = array();
foreach($product->getElementsByTagName('name') as $name ) {
// Stick $name onto the array
$append[] = $name;
}
foreach ($append as $a) {
$parent_node->appendChild($xml->createElement($a, 'anothervalue'));
$product->appendChild($parent_node);
}
$product->removeChild($xml->getElementsByTagName('details')->item(0));
//$product->appendChild($element);
}
// final result:
$result = $xml->saveXML();
Original XML structure:
<products>
<product>
<name>text</name>
<name>text</name>
<name>text</name>
</product>
</products>
I'm trying to create a new element whose value is the text of itself. I know what it has to look like. Why can't I use an object to create an element?
The result I'm trying to obtain will look like this:
<products>
<product>
<text>text</text>
<text>text</text>
<text>text</text>
</product>
</products>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您无法传递对象,必须使用
textContent
或nodeValue
属性:您可能还想首先将其从非法字符中删除:
You can't pass an object, you must use the
textContent
ornodeValue
properties:You may also want to strip it from illegal characters first:
在 foreach 循环之前声明数组,否则每次循环完成时数组都会变空
declare the array befor the foreach loop otherwise it will become empty every time when one loop will complete
这个获取元素值,如果你想获取元素名称..使用'
$a->nodeName
'This get element value, if you wanna get the element name .. use '
$a->nodeName
'只需更改这一行
$append[] = $name;
到
$append[] = $name->tagName;
那么它应该可以工作
Just change this one line
$append[] = $name;
to
$append[] = $name->tagName;
It should work then