簡體   English   中英

在php中讀取xml數據

[英]Read xml data in php

我有一個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>

我需要將其保存在數據庫中,我只是使用下面的代碼來保存數據

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; 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
)

是否有獲取所有這些數據的方法。

如果您不使用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()允許您使用表達式從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()獲取節點數組。 這不是獲取標量值的直接方法,但是已實現的magic方法允許緊湊的語法。

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

你可以舉個例子

 $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