douwei1174 2011-04-06 15:33
浏览 93

如何在PHP中将XML字符串转换为DOMDocument?

I got an example XML string from a customer, which I would like to transform to a DOMDocument. I can't seem to get the first node right though....

The string looks like this;

<ev:Events xmlns:ev="xsdEvents" xsi:schemaLocation="xsdEvents [url]" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Node>
        <OtherNode>value</OtherNode>
    </Node>
</ev:Events>

How would I set this up the proper way via DOMDocument in PHP?

  • 写回答

1条回答 默认 最新

  • dsp15140275697 2011-04-06 16:25
    关注

    Well, loading a XML string to a DOMDocument object is not quite that hard -- you'll just have to use DOMDocument::loadXML().

    For example, in your case, you'd use :

    $string = <<<XML
    <ev:Events xmlns:ev="xsdEvents" xsi:schemaLocation="xsdEvents [url]" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <Node>
            <OtherNode>value</OtherNode>
        </Node>
    </ev:Events>
    XML;
    
    $dom = new DOMDocument();
    $dom->loadXML($string);
    


    Then, accessing your data is just a matter of using the relevant DOM methods.

    For example, to extract the value of your <OtherNode> node, you could use :

    $items = $dom->getElementsByTagName('OtherNode');
    if ($items->length > 0) {
      var_dump( $items->item(0)->nodeValue );
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计