0

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!

JD Isaacks
  • 56,088
  • 93
  • 276
  • 422

4 Answers4

1

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
}
Christophe Eblé
  • 8,071
  • 3
  • 33
  • 32
0

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
  • 56,385
  • 11
  • 85
  • 79
0

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
  • 28,292
  • 6
  • 45
  • 57
0

I think the easiest is:

$dom = domxml_open_mem($str);
$keywords = $dom->get_elements_by_tagname('keyword');
Christophe Eblé
  • 8,071
  • 3
  • 33
  • 32