【问题标题】:Freemind map xml parsing get last childs with simplexml phpFreemind map xml解析使用simplexml php获取最后一个孩子
【发布时间】:2014-07-02 17:09:53
【问题描述】:

我在使用 SimpleXML 解析 XML 文件时遇到问题,实际上是 freemind 映射。

XML 示例:

<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>

通过以下代码,我可以获得所有孩子:

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);
}

我想要得到的只是所有最后一个孩子的 TEXT 值,实际上是不包含孩子的节点。

任何帮助将不胜感激

提前致谢!

【问题讨论】:

    标签: php xml parsing simplexml freemind


    【解决方案1】:

    您可以使用SimpleXMLElement::xpatharray_map 轻松做到这一点。

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

    您可以看到,首先我们得到一个 node that do not have children 数组,然后我们将每个节点转换为包含该节点的 TEXT 属性的字符串。

    【讨论】:

    • 谢谢蒂姆,使用 var_dump 我可以看到它有效,但对我来说并不容易,我的 php 接近基本水平。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多