php获取xml内部标记内容
我需要执行一个API,它的响应是XML。 但是XML值在XML标记中 比如说php获取xml内部标记内容,php,xml,Php,Xml,我需要执行一个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"/> &l
<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>
ThanxXPath:
不是强制性的,您可以只获取所有子节点并循环遍历它们,但是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();
}
或者您可以使用DomeElement
$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++;
}
children()作为$item)
{
$prodidz[]=$item->attributes()->productid;
$prodnamez[]=$item->attributes()->productname;
$costz[]=$item->attributes()->成本;
}
?>
$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++;
}
<?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;
}
?>