xpath help

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
wackyakmed
Forum Newbie
Posts: 12
Joined: Sat Dec 16, 2006 10:37 am

xpath help

Post by wackyakmed »

I'm trying to use xpath to pick out a node name from an xml input string. A sample of the xml I'll be parsing:
<?xml version="1.0" encoding="UTF-8"?><request account="xxxxx" password="xxxxxx"><send param1="test" param2="ececececec" /></request>
I need to pick out the child node of "request." That node name, which is "send" in this example, can be one of four or five different names, like "groups," "join," etc. I've tried using this code to pick out the "send" node name:

Code: Select all

function getCommandReq($req)
{
	$result = $req->xpath('/request/*');
	$reqCommand = (string) key($result[0]);
	echo '***REQUEST COMMAND: ', $reqCommand, '***';

}
This code returns:

Code: Select all

***REQUEST COMMAND: @attributes***
I don't think I'm doing the node navigation correctly, but this is how I interpreted the implementation from the xpath tutorials I've read. Can anyone give advice as to where I'm going wrong? Thanks very much.
wackyakmed
Forum Newbie
Posts: 12
Joined: Sat Dec 16, 2006 10:37 am

Post by wackyakmed »

One thing that I forgot to mention: $req is passed a reference of

Code: Select all

$request = simplexml_load_string($xml);
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

try

Code: Select all

<?php
$xml = '<?xml version="1.0" encoding="UTF-8"?><request account="xxxxx" password="xxxxxx"><send param1="test" param2="ececececec" /></request>';
$req = simplexml_load_string($xml);
$result = $req->xpath('/request/*');

foreach($result as $node) {
	switch($node->getName()) {
		case 'send':
			echo 'send: ', $node['param1'], "<br />\n";
			break;
		default:
			echo '<div>unknown element</div>';
			break;
	}
}
wackyakmed
Forum Newbie
Posts: 12
Joined: Sat Dec 16, 2006 10:37 am

Post by wackyakmed »

Works great, thanks Volka!
Post Reply