Reputation: 15
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!
Upvotes: 0
Views: 173
Reputation:
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.
Upvotes: 0