0

Recently I am using php to deal with a xml file.

But I don't know how to add a 'break' in my code.

The link is : http://babystory.diandian.com/rss

I want to use php to get the article named '[x]快乐王子'.But "foreach()" give me the last article named '[1]狼和七只小山羊'.

I want to add a break in "foreach()" so that I can get the article I want.

Here is my php code:

<?php
$xml = simplexml_load_file("http://babystory.diandian.com/rss");

foreach($xml->children() as $child){}

foreach($child->children() as $child2)

foreach($child2->children() as $child3)
{
  $element = $child3->getName();
  if($element=='title')
  {
    echo "<h1>" . $child3 . "</h1>";
  }

  if($element=='description')
  {
    echo $child3;
  }
}
?>

Could you help me to edit my code.Thank you very much.

3
  • Simple use break statement. If you want break 2 cycles, use break 2; Commented Jan 15, 2012 at 16:29
  • When I run you code, I get all three stories -- not just one. And what are you trying to accomplish exactly? Do you want to exit parsing once you hit that story? Commented Jan 15, 2012 at 16:32
  • I want to get one story from the xml.If you open the xml,you can see there are three <item> elements.I want to get the first one not the last one.But now I don't know how to achieve it. Commented Jan 15, 2012 at 16:39

2 Answers 2

2

If you need to get the first item from your feed you don't need any foreach loops at all.

$xml = simplexml_load_file("http://babystory.diandian.com/rss");
$item = (array)$xml->channel->item[0]; // the article [x]快乐王子 array

Now $item is array of the first article information. So $item['title'] is [x]快乐王子, $item['link'] is http://babystory.diandian.com/post/2012-01-15/14770976, etc.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much.You helped me to use array to solve the problem and also helped my to review the skill of programming.
0

Try this inside your last foreach....

i.e. .....

foreach($child2->children() as $child3){
   if($child3->getName() == "title" && $child3 == "THE TITLE I WANT"){
       $saveItem = $child3;
       break 3;
   }
}
echo $saveItem;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.