Page 1 of 1

xpath help

Posted: Mon Dec 18, 2006 9:09 am
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.

Posted: Mon Dec 18, 2006 9:27 am
by wackyakmed
One thing that I forgot to mention: $req is passed a reference of

Code: Select all

$request = simplexml_load_string($xml);

Posted: Mon Dec 18, 2006 9:47 am
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;
	}
}

Posted: Mon Dec 18, 2006 9:59 am
by wackyakmed
Works great, thanks Volka!