Jump to content

Extract CData from XML (PHP / SimpleXML)


Hybride

Recommended Posts

I know this is very simple, but alas, I can't figure it out.  I need to grab the CData from an XML file using SimpleXML, loop through every item in the XML file, pick out specific products and then put them in a different file.

 

Using

	echo "<pre>",print_r($xml,true),"</pre>";

the structure goes as

    - id
   - title
    [items]
            - item
                     - model
                     - title
                     - category

or basically $xml->items->item then whatever node I need. It's the title that has the <![CDATA[whatever]]> and I can't figure out how to extract that information as well. It just shows up as SimpleXMLElement Object. I tried to do something along the lines of:

    $xml = simplexml_load_file('products.xml');

if($xml->items->item->category == ";whatever;") {
	print $xml->items->item;
}

Where assuming the category is what I need, then only the items are printed (but I realised this is more of a Perl thing and I became confused.) I tried looking at these pages: Reading XML with elements and attributes and Extract XML via PHP which helped, but this is the first am actually doing XML->PHP work and not sure how to actually do it.

 

Any help would be sincerely appreciated.

Link to comment
Share on other sites

Actually, I managed to figure it out (somehow that keeps happening after I post on this forum)...

 

To those interested,

 

   $xml = simplexml_load_file('products.xml');foreach ($xml->items->item as $cat) {	preg_match('#whatever#i',$cat->category,$matches);	if($matches[0]) {			echo $cat->title.'<br/>';		echo $cat->model.'<br/>';		echo $cat->price.'<br/>';	}}

 

It loops through the entire document, finding only whatever you're trying to match, printing the respected title/model/price, though that can easily be changed to fit your needs.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.