Find XML nodes

Hey,
I have a PHP array and an XML file structured like below:

<?xml version="1.0"?>
<question_list>
	<question>
		<id>
			1
		</id>
		<text>
			What is a Cat?
		</text>
	</question>
	<question>
		<id>
			2
		</id>
		<text>
			What is your name?
		</text>
	</question>
	<question>
		<id>
			3
		</id>
		<text>
			Where are you now?
		</text>
	</question>
	<question>
		<id>
			5
		</id>
		<text>
			Where is Brazil?
		</text>
	</question>
</question_list>

How can I search using SimpleXML through my xml file to find all questions which have id’s which are in the PHP array?

Thanks,

Regards,
Neil

Try something like this (untested):


$ids = array(1,3,5);
$result = array();

$doc = simplexml_load_string('<your xml>');

foreach ($doc->question_list as $question)
{
    if (in_array((integer) $question->id, $ids))
    {
        $result[] = $question->name;
    }
}

return $result;

Hey Thanks, I just about to understandit but could you just confirm the below:

foreach ($doc->question_list as $question)

The above is saying: "For each, nope i’m already confused as to what and how this is working, ha ha ha, need soem help here.

and

if (in_array((integer) $question->id, $ids)) is saying:

“If the id of a specific question is a a valid integer and is in the array called $ids thendo something?”

foreach: http://uk2.php.net/manual/en/control-structures.foreach.php

The first part ($doc->question_list) is always an array (or Iterable object, but forget about that just now).

The second part is the name of a variable to be created.

Each value in the array is put into the named variable, letting you do whatever you want with it.

in_array: http://uk3.php.net/in_array

First parameter is the “needle” and the second is the “haystick” (like the metaphor).

The function looks inside the array for the needle.

“(integer)” just casts the needle’s value to an integer (e.g. from a string). It isn’t necessary, probably.

Does that help?

ok Thanks