2016-10-10 82 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

感谢这个! :) –