• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 531
  • Last Modified:

php xml get value of node

How can I get "bla" in the below dump of my node
Essentially bla is what is contained in my node
<mynode name="myvalueone" display="myvalue2">bla</mynode>

object(SimpleXMLElement)[21]
  public '@attributes' => 
    array
      'name' => string 'myvalueone' (length=65)
      'display' => string 'myvalue2' (length=9)
  string 'bla' (length=3)

Open in new window

0
NewtonianB
Asked:
NewtonianB
1 Solution
 
ropennerCommented:
The code below traverses the simplexml object and you can see the text gets printed out where there are no children of a node (therefore a leaf node) and the resulting string has a length greater than zero.

If you want to find the text for a specific node then add code to compare the $node->getName() to the one you want and then find the child node with no children.

Making alterations to this code should familiarize yourself with what is all in the returned simplexml object.

You can also run an xpath query which returns specific text from a input query.  Explained in the manual here:

http://www.php.net/manual/en/simplexmlelement.xpath.php

for your example the command would look like:

$result = $sxml->xpath('/mynode');
foreach ($result as $oneresult) {
    echo "found", $oneresult, "<BR>";
}

<?php
      echo '<PRE>';
       $xml_file = "????.htmlorxml";
	$sxml = simplexml_load_file($xml_file,'SimpleXMLElement',LIBXML_NOCDATA);
	print_r($sxml);
	var_dump($sxml);
	echo '</pre>';

	print dumpIt($sxml);
	
function dumpIt($node) {
	$output = "<DIV style=\"padding: 0px 0px 0px 20px;\">".$node->getName()."\n";
	$att = $node->attributes();
	if ($att) {  // is false if there are no attributes
		$output .= "<UL>";
		foreach ($att as $att_key => $att_value) {
			$output .= "<LI> [".$att_key ."] = ".$att_value;
		}
		$output .= "</UL>";
	}
	if ($node->count() == 0) { // check for leaf node
		$node_text = (string)$node;
		if (strlen($node_text) > 0) {
			$output .= "<UL>[internal text] = ". trim($node) ."</UL>\n";				
		}
	} else {
		foreach ($node as $key => $value) {
			$output .= dumpIt($value);
		}
	}
	$output .= "</DIV><BR>\n";
	return $output;
}
?>

Open in new window

0
 
NewtonianBAuthor Commented:
thx
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now