【问题标题】:PHP SimpleXML, how to set attributes?PHP SimpleXML,如何设置属性?
【发布时间】:2011-01-23 03:50:26
【问题描述】:

如果你有类似的东西,

<hello id="1" name="myName1">
 <anotherTag title="Hello">
 </anotherTag>
</hello>
<hello id="2" name="myName2">
 <anotherTag title="Hi">
 </anotherTag>
</hello>

如何将 hello id 2 的属性更改为 name="William" ?还是标题你好?

非常感谢您的关注, H'

【问题讨论】:

    标签: php attributes set simplexml


    【解决方案1】:

    记住,您的 XML 文档必须有一个根元素:

    $xml = simplexml_load_string("<root>$string</root>");
    $xml->hello[1]['name'] = 'John Doe';
    $xml->hello[1]->anotherTag['title'] = 'Hello';
    echo $xml->asXml();
    

    要保存文件,请使用asXML($filename)

    【讨论】:

      【解决方案2】:

      如果你想使用 simplexml 在根元素上设置一个属性,你可以这样做:

      $xml['name'] = "william";
      

      但是,对于列出的示例,前面的海报是正确的;您需要添加一个顶级元素。

      【讨论】:

        【解决方案3】:
        $xml[0]['name'] = "newname";
        

        我相信这是编辑您那里的 XML 文档的另一种方法。
        我使用的这种方法将适用于提供的 XML 文件。
        他可以像在“第一个”示例。
        这使他不必在标签中进行下去。

        【讨论】:

          猜你喜欢
          • 2012-05-19
          • 2012-09-08
          • 1970-01-01
          • 2012-06-21
          • 1970-01-01
          • 2018-08-04
          • 2014-04-26
          相关资源
          最近更新 更多