tags:

views:

384

answers:

4

I am not totally new to PHP or XML but I am 100% new to paring XML with PHP. I have an XML string that has several nodes but the only ones I am insterested in are the < keyword > nodes which there are an uncertain number of each containing a phrase like so: < keyword >blue diamond jewelry< /keyword > for example say the string looked like this:

<xml>
<pointless_node/>
<seq>
<keyword>diamond ring</keyword>
<keyword>ruby necklace</keyword>
<keyword>mens watch</keyword>
</seq>
<some_node/>
</xml>

I would want an array like this:

['diamond ring','ruby necklace','mens watch']

I tried looking at the PHP manual and just get confused and not sure what to do. Can someone please walk me through how to do this? I am using PHP4.

THANKS!

A: 

see: http://www.php.net/simplexml-element-xpath Try the following xpath and array construction

$string = "<xml>
<pointless_node/>
<seq>
<keyword>diamond ring</keyword>
<keyword>ruby necklace</keyword>
<keyword>mens watch</keyword>
</seq>
<some_node/>
</xml>";

$xml = domxml_open_mem($xmlstr)

$xpath = $xml->xpath_new_context();
$result = xpath_eval($xpath,'//keyword');

foreach ($result->nodeset as $node)
{
     $result[] = $node->dump_node($node);
}

edit: modified code to reflect php 4 requirements edit: modified to account for poorly documented behaviour of xpath_new_context (php docs comments point out the error)

Jonathan Fingland
Isn't simplexml only for php-versions > 5?
Silfverstrom
I’d even use `//keyword/text()` xpath
Maciej Łebkowski
ah... *checks docs* quite right.... back to the drawing board.
Jonathan Fingland
modified to use domxml from php 4. untested as I don't have access to a server with php 4
Jonathan Fingland
Thanks I tried this and I get this error: Warning: xpath_new_context() expects parameter 1 to be object, boolean given.
John Isaacks
changed $xpath = xpath_new_context(); to $xpath = $xml->xpath_new_context();
Jonathan Fingland
A: 

XML_Parser->xml_parse_into_struct() might be what you're looking for. Works for Php versions >= 4

http://se.php.net/xml_parse_into_struct
http://www.w3schools.com/PHP/func_xml_parse_into_struct.asp

Silfverstrom
A: 

I think the easiest is:

$dom = domxml_open_mem($str);
$keywords = $dom->get_elements_by_tagname('keyword');
SleepyCod
This turns $keywords into an array of Objects. Is there a way to get the text from the objects?
John Isaacks
+1  A: 

This turns $keywords into an array of Objects. Is there a way to get the text from the objects?

Sure, see this.

$dom = domxml_open_mem($str);
$keywords = $dom->get_elements_by_tagname('keyword');

foreach($keywords as $keyword) {
    $text = $keyword->get_content();
    // Whatever
}
SleepyCod
I really appreciate you taking the time to answer my questions, unfortunately in the code you posted $text == 'Object' not the text in the tags.
John Isaacks
My bad, use $text = $keyword->get_content();
SleepyCod
Yes that worked! thanks!
John Isaacks