在php中读取xml数据

时间:2016-09-28 09:35:05

标签: php 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>

我需要将其保存在db中,我只是使用下面的代码来保存数据

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;

        }
    }
}

我需要获得<key type="your_id">CYBEX-525A/DA-IPOD</key><key type="web">cybex-525at-arc-trainer</key>的价值但无法获取数据 当我在循环中打印echo '<pre>'; print_r($item->key) ; die;时,我正在跟随放置:

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
)

是否有任何获取所有这些数据的方法。

3 个答案:

答案 0 :(得分:1)

如果您不能使用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
}

答案 1 :(得分:1)

DOMXpath::evaluate()允许您使用表达式从XML DOM中获取节点和标量值。表达式定义结果是节点列表还是标量值。您可以使用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)
      ]
    );
  }
}

输出:

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

第二个参数或DOMXpath::evaluate()是表达式的上下文。因此,很容易迭代节点列表并为它们获取数据。

string()这样的Xpath函数将列表的第一个节点作为标量值。如果列表为空,则返回该类型的空值。

SimpleXML允许您使用SimpleXMLElement::xpath()获取节点数组。这里没有直接获取标量值的方法,但实现的魔术方法允许使用紧凑的语法。

您必须将返回的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
      ]
    );
  }
}

答案 2 :(得分:0)

您可以使用

作为示例

var startDate = DateTime.ParseExact(Console.ReadLine(),
             "dd.M.yyyy", CultureInfo.InvariantCulture);