从XML字符串中获取文本

时间:2016-05-25 16:48:14

标签: php

我试图通过http://www.fta.co.uk/feeds/daily_fuel_price.xml

的xml文件获取最新日期的批量柴油价格

我使用simplexml_load_string来获取频道项描述,这是一个字符串。

Latest fuel prices at 24 May 2016<p>86.28ppl<br>88.84ppl<br>39.31ppl<br></p><p>PricesfromAccenture</p>

我需要这个价值86.28ppl,这是批量柴油价格。我怎么得到这个。我尝试使用<br>进行爆炸,然后再次使用<p>进行爆炸尝试将值放入数组中,但仍显示完整的字符串。

我如何解决?

以下是完整的代码,亲自试试

 $url = "http://www.fta.co.uk/feeds/daily_fuel_price.xml";
    if (($response_xml_data = file_get_contents($url))===false){
        echo "Error fetching XML\n";
    } else {
       libxml_use_internal_errors(true);
       $data = simplexml_load_string($response_xml_data);
       if (!$data) {
           echo "Error loading XML\n";
           foreach(libxml_get_errors() as $error) {
               echo "\t", $error->message;
           }
       } else {
      //    echo "<pre>";
       //$data = simplexml_load_string($data->channel->item->description);
       foreach ($data->channel->item as $entry){
        echo $entry->title;
      //echo $entry->description;
      $str = preg_replace('#(<b.*?>).*?(</b>)#', '$1$2', $entry->description); //remove text between bold tags

      $str = str_replace("<b></b>","",$str); //remove bold tags
    $str = preg_replace('/\s+/', '', $str);  //remove whitespace
   $arr = explode("<p>", $str);

    $arr = explode("<br>", $arr[1]);
    echo $arr[0];
      break;
       }
       //echo "</pre>";
       }
    }

2 个答案:

答案 0 :(得分:0)

只需执行此操作:Online Check

$str = 'Latest fuel prices at 24 May 2016<p>86.28ppl<br>88.84ppl<br>39.31ppl<br></p><p>PricesfromAccenture</p>';

$arr = explode("<p>", $str);

$arr = explode("<br>", $arr[1]);
echo $arr[0]; //86.28ppl

答案 1 :(得分:0)

链接中description标记的内容与问题中的内容不同。在链接中,可以这样处理:

  $arr = explode("<p>", $entry->description);
  $arr = explode("</b>", $arr[1]);
  $arr = explode("<br", $arr[1]);
  $desc = trim($arr[0]); // 86.28ppl