我需要执行一个API,它的响应是XML。 但XML值在XML标记内。
例如
<example>
<item productid = "1" productname = "xxx" cost = "5.3"/>
<item productid = "2" productname = "yyy" cost = "4.0"/>
<item productid = "3" productname = "zzz" cost = "1.75"/>
</example>
任何人都可以告诉我我怎样才能在标签之间移动并获得元素值 例如:
example:
item:
productid -> 1,
productname -> xxx,
cost -> 5.3
item:
productid -> 2,
productname -> yyy,
cost -> 4.0
item:
productid -> 3,
productname -> zzz,
cost -> 1.75
感谢名单
答案 0 :(得分:1)
的XPath: http://php.net/manual/en/simplexmlelement.xpath.php
不是强制性的,你可以让所有的孩子循环使用它们,但XPath在现实世界的场景中更通用(你有多个级别的XML节点)并且更具可读性。
<?php
$xmlStr = <<<END
<example>
<item productid = "1" productname = "xxx" cost = "5.3"/>
<item productid = "2" productname = "yyy" cost = "4.0"/>
<item productid = "3" productname = "zzz" cost = "1.75"/>
</example>
END;
$xml = new SimpleXMLElement($xmlStr);
$items = $xml->xpath("//example/item");
$out = array();
foreach($items as $x) {
$out [] = $x->attributes();
}
答案 1 :(得分:1)
或者您可以使用DOMElement
$doc = new DOMDocument();
$doc->load('domexample.xml');
$elements = $doc->getElementsByTagName('item');
$x = 0;
foreach($elements as $element)
{
$results[$x]['productid'] = $element->getAttribute('productid');
$results[$x]['productname'] = $element->getAttribute('productname');
$results[$x]['cost'] = $element->getAttribute('cost');
$x++;
}
答案 2 :(得分:0)
<?php
$file = "filename.xml";
$example = simplexml_load_file($file) or die("Error: Can't Open File");
$prodidz = array();
$prodnamez = array();
$costz = array();
foreach ($example->children() as $item)
{
$prodidz[] = $item->attributes()->productid;
$prodnamez[] = $item->attributes()->productname;
$costz[] = $item->attributes()->cost;
}
?>