如何在不使用SimpleXmlElement父元素的情况下设置其文本值?

编程入门 行业动态 更新时间:2024-10-25 08:28:04
本文介绍了如何在不使用SimpleXmlElement父元素的情况下设置其文本值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想设置xpath()找到的某个节点的文本

I want to set text of some node found by xpath()

<?php $args = new SimpleXmlElement( <<<XML <a> <b> <c>text</c> <c>stuff</c> </b> <d> <c>code</c> </d> </a> XML ); // I want to set text of some node found by xpath // Let's take (//c) for example // convoluted and I can't be sure I'm setting right node $firstC = reset($args->xpath("//c[1]/parent::*")); $firstC->c[0] = "test 1"; // like here: Found node is not actually third in its parent. $firstC = reset($args->xpath("(//c)[3]/parent::*")); $firstC->c[2] = "test 2"; // following won't work for obvious reasons, // some setText() method would be perfect but I can't find nothing similar, $firstC = reset($args->xpath("//c[1]")); $firstC = "test"; // maybe there's some hack for it? $firstC = reset($args->xpath("//c[1]")); $firstC->{"."} = "test"; // nope, just adds child named . $firstC->{""} = "test"; // still not right, 'Cannot write or create unnamed element' $firstC["."] = "test"; // still no luck, adds attribute named . $firstC[""] = "test"; // still no luck, 'Cannot write or create unnamed attribute' $firstC->addChild('','test'); // grr, 'SimpleXMLElement::addChild(): Element name is required' $firstC->addChild('.','test'); // just adds another child with name . echo $args->asXML(); // it outputs: // // PHP Warning: main(): Cannot add element c number 2 when only 1 such elements exist // PHP Warning: main(): Cannot write or create unnamed element // PHP Warning: main(): Cannot write or create unnamed attribute // PHP Warning: SimpleXMLElement::addChild(): Element name is required // <?xml version="1.0"? > // <a> // <b> // <c .="test">test 1<.>test</.><.>test</.></c> // <c>stuff</c> // </b> // <d> // <c>code</c> // <c>test 2</c></d> // </a>

推荐答案

您可以使用 SimpleXMLElement自引用:

$firstC->{0} = "Victory!!"; // hackity, hack, hack! // -or- $firstC[0] = "Victory!!";

看过后发现

var_dump((array) reset($xml->xpath("(//c)[3]")))

这也适用于答案中概述的unset操作:

This also works with unset operations as outlined in an answer to:

  • 在PHP的SimpleXML中删除具有特定属性的孩子

更多推荐

如何在不使用SimpleXmlElement父元素的情况下设置其文本值?

本文发布于:2023-11-11 06:52:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1577684.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:情况下   元素   文本   如何在   SimpleXmlElement

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!