Jump to content

Query XML for specific data


RabPHP

Recommended Posts

Greetings,

I need to know if it is possible to query an XML file for something specific.

For example...

I have an XML data that looks like...

<news>
<story>
<headline>Story1</headline>
<description>description of Story1 </description>
</story>
<story>
<headline>Story2</headline>
<description>Description of Story2</description>
</story>
</news>

What I would like to do is essentially "SELECT description from (file) where headline='story2';

Is there anyway to do something like that with PHP and XML?

Rab
Link to comment
Share on other sites

I've been looking over the SimpleXML function, however I can't seem to find any examples of what I am looking for.

I have found out how to pull out everything in a specific node, but not how to pull out information in a node where another node on the same level equals something.  Anyone out there have an example?

Rab

Rab
Link to comment
Share on other sites

Ive never used it myself but maybe something like....

[code]
<?php
  $xmlstring = file_get_contents("yourfile.xml");
  $xml = new SimpleXMLElement($xmlstring);
  foreach ($xml->story as $story) {
    if (strtolower($story->headline) == "story2") {
      echo $story->description;
    }
  }
?>
[/code]
Link to comment
Share on other sites

That worked!  I've been trying to do this myself for almost a week.

Only 1 small problem.  The XML file has a New Line after the entries in the description.  For example...


<description>description of Story1
This is a cool movie
This gets 5 stars
</description>

With the code below it's displaying...

description of Story1 This is a cool movie This gets 5 stars

How can I get it to take the New Line markers and display it on a new line?



Rab
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.