2016-10-10 81 views
0

我有這個XML文件getItems.php用PHP搜索XML文件?

<items> 
    <item name="Designer: X091" price="300"> 
    <det set="10"> 
     <data> 
     <![CDATA[ 
     [{"c": 10092, "l": "", "hasItem": false}] 
     ]]> 
     </data> 
    </det> 
    </item> 
    <item name="Designer: X091" price="10"> 
    <det set="2"> 
     <data> 
     <![CDATA[ 
     [{"c": 19920, "l": "", "hasItem": false}] 
     ]]> 
     </data> 
    </det> 
    </item> 
</items> 

我想要做的是提取項目名稱和價格,並det的設置數量,並且裏面有什麼data變量,我想使用foreach,因此如果商品名稱是「設計師:X091」,我可以得到每件商品,

我正在嘗試這answer,但我有點困惑與xpath,並希望得到一些幫助。謝謝:)

回答

1

在這裏你有一個使用SimpleXML搜索該特定元素並顯示其信息。

我已經使用while循環代替foreach停止搜索,當你找到你想要的元素。

<?php 

$string = ' 
<items> 
    <item name="Designer: X091" price="300"> 
    <det set="10"> 
     <data> 
     <![CDATA[ 
     [{"c": 10092, "l": "", "hasItem": false}] 
     ]]> 
     </data> 
    </det> 
    </item> 
    <item name="Designer: X091" price="10"> 
    <det set="2"> 
     <data> 
     <![CDATA[ 
     [{"c": 19920, "l": "", "hasItem": false}] 
     ]]> 
     </data> 
    </det> 
    </item> 
</items>'; 

$obj = new SimpleXMLElement($string); 

$searchedName = 'Designer: X091'; 
$numberOfItems = count($obj->item); 
$i = 0; 

// While you don't find it and there're elements left, look for the next 

while($obj->item[$i]['name'] != $searchedName && $i < $numberOfItems){ 
    $i++; 
} 

// If the counter is NOT less than number of items, we didn't find it 

if($i == $numberOfItems){ 
    echo 'Item not found'; 
} 

// Else, we know the position of the item in the object 

else{ 
    $price = $obj->item[$i]['price']; 
    $detSet = $obj->item[$i]->det['set']; 
    $data = $obj->item[$i]->det->data; 
} 

echo "Name: $searchedName<br>"; 
echo "Price: $price<br>"; 
echo "Det set: $detSet<br>"; 
echo "Data: $data<br>"; 

輸出是:

 
Name: Designer: X091 
Price: 300 
Det set: 10 
Data: [{"c": 10092, "l": "", "hasItem": false}] 
1

把你的XML $xmlString變量,那麼:

// create a new instance of SimpleXMLElement 
$xml = new SimpleXMLElement($xmlString); 
$results = []; 

// check how many elements are in your xml 
if ($xml->count() > 0) { 

    // if more than 0, then create loop 
    foreach ($xml->children() as $xmlChild) { 

     // assign attributes to $attr variable 
     $attr = $xmlChild->attributes(); 

     // check if your attrs are defined 
     if (isset($attr['name']) && isset($attr['price'])) { 

      // attach values to $results array 
      $results[] = [ 
       'name' => (string)$attr['name'], 
       'price' => (int)$attr['price'] 
      ]; 
     } 
    } 
} 

然後可變$results應該是這樣的:

Array 
(
    [0] => Array 
     (
      [name] => Designer: X091 
      [price] => 300 
     ) 

    [1] => Array 
     (
      [name] => Designer: X091 
      [price] => 10 
     ) 

) 
+0

感謝這個! :) –