douhu2890 2014-05-14 14:52
浏览 59
已采纳

Freemind map xml解析使用simplexml php获取最后一个子节点

I am having an issue when parsing with SimpleXML an XML file what actually freemind map.

XML example:

<map version="1.0.1">
<node TEXT="str_1">
    <node TEXT="str_2">
        <node TEXT="str_3"/>
        <node TEXT="str_4">
            <node TEXT="str_5">
                <node TEXT="str_6"/>
            </node>
            <node TEXT="$ str_7"/>
            <node TEXT="str_8"/>
            <node TEXT="$ str_9"/>
        </node>
    </node>
    <node TEXT="str_10"/>
    <node TEXT="str_11"/>
    <node TEXT="$ str_12"/>
</node>
</map>

And with folowing code i can get all childs:

function print_node_info($father, $node)
{

        $output_xml = $node['TEXT'].' - Son of - '.$father.'</br>';

        echo $output_xml;

            // $file = 'output.xml';
            // // Open the file to get existing content
            // $output_xml .= file_get_contents($file);
            // // Write the contents back to the file
            // file_put_contents($file, $output_xml);

                //echo 'father: ' . $father.'<br>';
                //echo 'node: ' . $node['TEXT'].'<br><br>';
                foreach ($node->children() as $childe_node)
                //foreach $xml->xpath("//node[last()]")[0]->attributes() as $Id)
                //foreach ($node as $childe_node) 
                {
                    $GLOBALS['grandfather'] = $father;
                    print_node_info($node['TEXT'], $childe_node);
                }   
}

$xml = simplexml_load_file('1.xml');

foreach ($xml->children() as $first_node) {
print_node_info("top_name", $first_node);
}

What i am trying to get is only all last children's TEXT value, actually nodes which not contains children's.

Any help would be appreciated

Thanks in advance!

  • 写回答

1条回答 默认 最新

  • dougou6213 2014-05-14 14:59
    关注

    You can do this rather easily using SimpleXMLElement::xpath and array_map.

    $values = array_map(function($node) {
        return (string) $node['TEXT'];
    }, $xml->xpath('//node[not(node)]'));
    

    You can see that first we get an array of node that do not have children, then we transform each of those nodes into a string containing the node's TEXT attribute.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号