简体   繁体   English

在php中读取xml数据

[英]Read xml data in php

I have a xml file output.xml 我有一个xml文件output.xml

<?xml version="1.0" encoding="UTF-8"?>
<items>
  <item>
    <key type="your_id">CYBEX-525A/DA-IPOD</key>
    <key type="web">cybex-525at-arc-trainer</key>
    <key type="web">standard-console-2573</key>
    <key type="name">Cybex 525AT Arc Trainer</key>
    <key type="name">Standard console</key>
    <review>
      <order_id>1544346 1</order_id>
      <author_nick>Brock</author_nick>
      <author_email>bb@GMAIL.COM</author_email>
      <date type="accepted">2013-10-14</date>
      <comment type="overall">This cardio machine is exceptional. It works every part of your leg muscles if you rotate through the height settings and include calf-raises and squats during your routine. It also works your shoulders and biceps if you focus on working them while operating the arm poles. Unlike a standard elliptical it will raise your heart rate and cause you to sweat heavily soon after you start your routine. If you're a runner and are used to using a treadmill, you will feel satisfied after using this machine. It is kind of addictive because your body feels so good during and after use. I have combined 30 minutes on the treadmill with 30 minutes on the Arc for weight-loss, muscle tone, and cardiovascular training.</comment>
      <score type="overall">5</score>
    </review>
    </item>
</items>

I need to save it in db, I'm just using below code to save data 我需要将其保存在数据库中,我只是使用下面的代码来保存数据

if(file_exists('output.xml')){
    $languages = simplexml_load_file("output.xml");
    //echo '<pre>'; print_r($languages) ; die;
    foreach($languages as $item){
             echo '<pre>'; print_r($item->key) ; die;   
            foreach($item->review as $review){
                 $order_id    = $review[0]->order_id;
                 $authorName  = $review[0]->author_nick;
                 $authorEmail = strtolower($review[0]->author_email);
                 $comment     = $review[0]->comment;
                 $score       = $review[0]->score;
                 $date        = $review[0]->date;

        }
    }
}

I need to get value of <key type="your_id">CYBEX-525A/DA-IPOD</key> and <key type="web">cybex-525at-arc-trainer</key> but unable to get data when i print echo '<pre>'; print_r($item->key) ; die; 我需要获取<key type="your_id">CYBEX-525A/DA-IPOD</key><key type="web">cybex-525at-arc-trainer</key>但无法获取数据当我打印echo '<pre>'; print_r($item->key) ; die; echo '<pre>'; print_r($item->key) ; die; within loop I'm getting following out put: 在循环内,我得到以下结果:

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [type] => your_id
        )

    [0] => CYBEX-525A/DA-IPOD
    [1] => cybex-525at-arc-trainer
    [2] => standard-console-2573
    [3] => Cybex 525AT Arc Trainer
    [4] => Standard console
)

Is there any method for get all these data. 是否有获取所有这些数据的方法。

If you won't use DOMDocument, you can try : 如果您不使用DOMDocument,可以尝试:

foreach($languages->item as $item){               //loop through item(s)
    foreach($item->key as $key) {                     //loop through key(s)
        if ($key["type"] == "your_id") echo $key;     //echo CYBEX-525A/DA-IPOD
    }

    print_r($item->review);                         //prints review data
}

DOMXpath::evaluate() allows you to use expression to fetch nodes and scalar values from an XML DOM. DOMXpath::evaluate()允许您使用表达式从XML DOM中获取节点和标量值。 The expression defines if the result is a node list or a scalar value. 该表达式定义结果是节点列表还是标量值。 You can iterate a node list with foreach() . 您可以使用foreach()迭代节点列表。

$document = new DOMDocument();
$document->loadXml($xmlString);
$xpath = new DOMXPath($document);

foreach ($xpath->evaluate('/items/item') as $item) {
  var_dump(
    [
      'id' => $xpath->evaluate('string(key[@type="your_id"])', $item)
    ]
  );
  foreach ($xpath->evaluate('review', $item) as $review) {
    var_dump(
      [
        'nick' => $xpath->evaluate('string(author_nick)', $review),
        'email' => $xpath->evaluate('string(author_email)', $review)
      ]
    );
  }
}

Output: 输出:

array(1) {
  ["id"]=>
  string(18) "CYBEX-525A/DA-IPOD"
}
array(2) {
  ["nick"]=>
  string(5) "Brock"
  ["email"]=>
  string(12) "bb@GMAIL.COM"
}

The second argument or DOMXpath::evaluate() is a context for the expression. 第二个参数或DOMXpath::evaluate()是表达式的上下文。 So it is easy to iterate a list of nodes and fetch data for them. 因此,很容易迭代节点列表并为其获取数据。

Xpath functions like string() case the first node of a list into a scalar value. string()这样的Xpath函数会将列表的第一个节点转换为标量值。 If the list was empty, and empty value of the type will be returned. 如果列表为空,则将返回该类型的空值。

SimpleXML allows you fetch arrays of nodes using SimpleXMLElement::xpath() . SimpleXML允许您使用SimpleXMLElement::xpath()获取节点数组。 Here is no direct way to fetch scalar values, but the implemented magic methods allow a compact syntax. 这不是获取标量值的直接方法,但是已实现的magic方法允许紧凑的语法。

You will have to cast the returned SimpleXMLElement objects into strings. 您将必须将返回的SimpleXMLElement对象转换为字符串。

$items = new SimpleXMLElement($xmlString);

foreach ($items->xpath('item') as $item) {
  var_dump(
    [
      'id' => (string)$item->xpath('key[@type="your_id"]')[0]
    ]
  );
  foreach ($item->xpath('review') as $review) {
    var_dump(
      [
        'nick' => (string)$review->author_nick,
        'email' => (string)$review->author_email
      ]
    );
  }
}

You can use as example 你可以举个例子

 $xml="".$rs_rssfeed['rss_url'].""; $xmlDoc = new DOMDocument(); $xmlDoc->load($xml); $xpath = new DOMXPath($xmlDoc); $count = $xpath->evaluate('count(//item)'); if($count>0) { $x=$xmlDoc->getElementsByTagName('item'); for ($i=0; $i<$count = $xpath->evaluate('count(//item)'); $i++) { $item_title=$x->item($i)->getElementsByTagName('title')->item(0)->nodeValue; $item_link=$x->item($i)->getElementsByTagName('link')->item(0)->nodeValue; $item_desc=$x->item($i)->getElementsByTagName('description')->item(0)->nodeValue; $item_pubdate=$x->item($i)->getElementsByTagName('pubDate')->item(0)->nodeValue; } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM