doujue1246 2013-04-02 08:38
浏览 34

SimpleXml如何在新创建的根元素中附加现有XML

I have some XML response from the server, but they don't have a root element, because of that I can't parse them with the new SimpleXML, so I need to create a root element and then add all those xml to this one created root element

 $res = bill_curl('GetAccounts'); //getting a list of accounts WITHOUT the <root> xml
 $xml = new SimpleXMLElement("<root></root>"); // creating a root element
 $xml->addChild($res); // adding to the <root> childrens

but the problem is:

1) the "<!--?xml version="1.0" encoding="UTF-8"?-->" stays inside and the same is at the top of the document

2) got some symbols like "<", "/>" how to remove them?

Updated:

  <document>
              <answer>
            <account>12345678</account>
            <info>someinfo</info>
            </answer>
             <answer>
            <account>23456789</account>
        <info>some info</info>
           </answer>
   </document>

this is what i've got after string manipulation then I make:

$xml = new SimpleXMLElement($str);

and here I get an error of start and ending tags mismatching, what I am missing here?

  • 写回答

1条回答 默认 最新

  • dongshanji3102 2013-04-02 08:51
    关注

    I'm not particularly keen on the brittleness of this solution. However, it sounds like you you're integrating against a flawed API, so I would suggest some basic string manipulation to get what you want:

    $str = '<?xml version="1.0" encoding="UTF-8"?><testing>2</testing><test2>1</test2>';
    // the above was a test string to represent the results of the below:
    $str = bill_curl('GetAccounts');
    
    // Switch the search string below with the actual doctype you're getting from the API.
    // It looks to have been commented out in your question which may or may not be the case.
    $str = str_replace('<?xml version="1.0" encoding="UTF-8"?>', '', $str);
    $str = '<root>'.$str.'</root>';
    
    $xml = new SimpleXMLElement($str);
    var_dump($xml);
    
    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能