2015-10-18 170 views
0

我需要执行一个API,它的响应是一个XML。 但是XML值在XML标签内。php获取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> 

谁能告诉我,我怎样才能,标签之间移动,并得到elemnt值 例如:

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 

感谢名单

回答

1

的XPath: http://php.net/manual/en/simplexmlelement.xpath.php

不需要atory,你可以得到所有的孩子并循环遍历它们,但是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

或者你可以使用一个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++; 
} 
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; 
} 

?>