Jump to content

Archived

This topic is now archived and is closed to further replies.

mwendel

PHP 5 Reading XML Element Values Directly from XML DOMDocument

Recommended Posts

Hi All,

Here's the issue

I have an XML Document that's structured like
<pre>
<foos>
    <foo>
      <d>Red</d>
      <e>Yellow</e>
      <f>Blue</f>
    </foo>
    <foo>
      <d>Orange</d>
      <e>Brown</e>
      <f>Green</f>
    </foo>
</foos>
</pre>
I create a new DOMDocument.  Load the File.  Do an XPath Query on it to get the <foo> element that contains
<pre>
<d>Red</d>
</pre>
I take that DOMNodeList (I think that's it) that is returned grab item(0) create a ne DOMDocument and Attach the Node to it.  So now I have XML stored in the new DOMDocument to deal with that looks like:
<pre>
<foo>
  <d>Red</d>
  <e>Yellow</e>
  <f>Blue</f>
</foo>
</pre>
How can I just grab the VALUE for //foo/d, //foo/e etcetera.  Keep in mind the assumption is that I know EXACTLY what the structure of <foo> is and I don't need to figure it out programmatically.

I have read most of the PHP Docs on the DOMDocument, DOMNodeList, DOMElement and I have been Googling to find the syntax needed to do this, but I am either missing it or there is a step in the middle I have to take.

Any help would be appreciated.

Thanks,

Michael

Share this post


Link to post
Share on other sites
[code]<?php
$data = simplexml_load_file('mwendel.xml');

foreach ($data as $foo) {
    if ($foo->d == 'Red')
        echo $foo->e, '<br>', $foo->f, '<br>';
}
?>[/code]

Share this post


Link to post
Share on other sites
Thanks.  I did it a little differently though because I didn't want to have to do the foreach loop since I only had one "record" so to speak.

I came up with this based upon an article I was reading on the web that I don't have the URL handy for because I closed my browser.

And just so everyone has the entire code and can tell me if I'm doing way too much work or not. I took out some of the conditional logic to check to make sure there were results in some cases.  But this is how the entire block of code ended up working out:

$dom = new DOMDocument();
$dom->load("mwendel.xml");
$xp = new DOMXPath($dom);

$check_value = "Red";

$result_xml_dom_query = $xp->query("//foos/foo[contains(d,$check_value)]");

$xml_node = $result_xml_dom_query->item(0);
$new_dom = new DOMDocument;
$new_dom->appendChild($new_dom->importNode($xml_node,1));

$simple_xml = simplexml_load_string($new_dom->saveXML());

$foo_d = $simple_xml->d;
$foo_e = $simple_xml->e;
$foo_f = $simple_xml->f;

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.