Search code examples
phpxmlphp4

PHP: Get array of text from perticular XML node type?


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!


Solution

  • 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
    }