用PHP搜索XML文件?

时间:2016-10-10 21:39:37

标签: php

我有这个XML文件getItems.php

<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内部对变量的内容,我想使用{{1所以我可以得到每个项目,如果项目的名称是“Designer:X091”

我正在尝试这个answer,但我对foreach感到困惑,并希望得到一些帮助。谢谢:))

2 个答案:

答案 0 :(得分: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
        )

)

答案 1 :(得分: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}]