douweng7083 2018-10-19 03:40
浏览 174
已采纳

将xml转换为json时,多个对象名称将更改为“@attributes”

I read this article.

https://qiita.com/yasumodev/items/74a73ed4b3f1dd45edb8

And I did the same thing.

// XML(RSSなど)を取得
$strXml = file_get_contents("./doc.xml");
// XML⇒JSONに変換
$strJson = xml_to_json($strXml);
// 出力
echo $strJson;

//**********************************
// XML ⇒ JSONに変換する関数
//**********************************
function xml_to_json($xml)
{
    // コロンをアンダーバーに(名前空間対策)
    $xml = preg_replace("/<([^>]+?):([^>]+?)>/", "<$1_$2>", $xml);
    // プロトコルのは元に戻す
    $xml = preg_replace("/_\/\//", "://", $xml);
    // XML文字列をオブジェクトに変換(CDATAも対象とする)
    $objXml = simplexml_load_string($xml, NULL, LIBXML_NOCDATA);
    // 属性を展開する
    xml_expand_attributes($objXml);
    // JSON形式の文字列に変換
    $json = json_encode($objXml, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    // "\/" ⇒ "/" に置換
    return preg_replace('/\\\\\//', '/', $json);
}

//**********************************
// XMLタグの属性を展開する関数
//**********************************
function xml_expand_attributes($node)
{
    if($node->count() > 0) {
        foreach($node->children() as $child)
        {
            foreach($child->attributes() as $key => $val) {
                $node->addChild($child->getName()."@".$key, $val);
            }
            xml_expand_attributes($child); // 再帰呼出
        }
    }
}

But in this way , several objects name change to "@attributes".

I want the original object name here(T_T)

Please help me.

  • 写回答

1条回答 默认 最新

  • dongpu42006096 2018-10-19 06:28
    关注

    When you json_encode() XML with attributes, this will create the @attributes elements your getting. The only way round this is to remove them as you expand them. I've changed the routine, the first thing is that I've put the part that processes the attributes first, this ensures that the root node gets processed as well.

    The main thing is that I've changed the way it works to use XPath to retrieve the attributes, this then encodes them as you have, but also allows you to remove the attribute from the original node (using unset($attribute[0]);)...

    function xml_expand_attributes($node)
    {
    
        foreach ($node->xpath("@*") as $attribute) {
            $node->addChild($node->getName()."@".$attribute->getName(), (string)$attribute);
            unset($attribute[0]);
        }
        if($node->count() > 0) {
            foreach($node->children() as $child)
            {
                xml_expand_attributes($child); // 再帰呼出
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题