XML到关联数组并回显特定值

时间:2014-02-12 16:42:40

标签: php xml arrays associative-array associative

我不确定我是否会以正确的方式解决这个问题,但我试图回应数组中的各个数据元素,但没有成功,我只需要从XML中获取大约10个变量以获得平均油耗在此处输入文件:https://www.fueleconomy.gov/ws/rest/ympg/shared/vehicles?make=honda&model=civic

我只需要make,model,year avgMpg这是youMpgVehicle等的一个孩子,所以我可以将它们放在一个表中,就像在PHP中回显SQL数据一样。

function download_page($path){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$path);
curl_setopt($ch, CURLOPT_FAILONERROR,1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
//curl_setopt($ch, CURLOPT_SSLVERSION,3); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
//curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); 

$retValue = curl_exec($ch);          
curl_close($ch);
return $retValue;
}

$sXML = download_page('https://www.fueleconomy.gov/ws/rest/ympg/shared/vehicles?make=honda&model=civic');
$oXML = new SimpleXMLElement($sXML);

$dom = new DomDocument();
$dom->loadXml($sXML);
$dataElements = $dom->getElementsByTagName('vehicle');
$array = array();
foreach ($dataElements as $element) {
$subarray = array();
foreach ($element->childNodes as $node) {
    if (!$node instanceof DomElement) {
        continue;
    }
    $key = $node->tagName;
    $value = $node->textContent;
    $subarray[$key] = $value;
 }
 $array[] = $subarray;
 // var_dump($array);  // returns the array as expected

var_dump($array[0]["barrels08"]); //how can I get this and other variables?


}

结构如下:(或者你可以点击上面的超链接)

-<vehicles>
-<vehicle>
<atvType/>
<barrels08>10.283832</barrels08>
<barrelsA08>0.0</barrelsA08>
<charge120>0.0</charge120>
<charge240>0.0</charge240>
<city08>28</city08>
<city08U>28.0743</city08U>
<cityA08>0</cityA08>
<cityA08U>0.0</cityA08U>
<cityCD>0.0</cityCD>
<cityE>0.0</cityE>
<cityUF>0.0</cityUF>
<co2>279</co2>
<co2A>-1</co2A>
<co2TailpipeAGpm>0.0</co2TailpipeAGpm>
<co2TailpipeGpm>279.0</co2TailpipeGpm>
<comb08>32</comb08>
<comb08U>31.9768</comb08U>
<combA08>0</combA08>
<combA08U>0.0</combA08U>
<combE>0.0</combE>
<combinedCD>0.0</combinedCD>
<combinedUF>0.0</combinedUF>
<cylinders>4</cylinders>
<displ>1.8</displ>
<drive>Front-Wheel Drive</drive>
<engId>18</engId>
<eng_dscr/>
<evMotor/>
<feScore>8</feScore>
<fuelCost08>1550</fuelCost08>
<fuelCostA08>0</fuelCostA08>
<fuelType>Regular</fuelType>
<fuelType1/>
<fuelType2/>
<ghgScore>8</ghgScore>
<ghgScoreA>-1</ghgScoreA>
<guzzler/>
<highway08>39</highway08>
<highway08U>38.5216</highway08U>
<highwayA08>0</highwayA08>
<highwayA08U>0.0</highwayA08U>
<highwayCD>0.0</highwayCD>
<highwayE>0.0</highwayE>
<highwayUF>0.0</highwayUF>
<hlv>0</hlv>
<hpv>0</hpv>
<id>33504</id>
<lv2>12</lv2>
<lv4>12</lv4>
<make>Honda</make>
<mfrCode>HNX</mfrCode>
<model>Civic</model>
<mpgData>Y</mpgData>
<phevBlended>false</phevBlended>
<pv2>83</pv2>
<pv4>95</pv4>
<rangeA/>
<rangeCityA>0.0</rangeCityA>
<rangeHwyA>0.0</rangeHwyA>
<trans_dscr/>
<trany>Automatic 5-spd</trany>
<UCity>36.4794</UCity>
<UCityA>0.0</UCityA>
<UHighway>55.5375</UHighway>
<UHighwayA>0.0</UHighwayA>
<VClass>Compact Cars</VClass>
<year>2013</year>
<youSaveSpend>3000</youSaveSpend>

-     33.612226599     45     55     47     28     16     33504                    

2 个答案:

答案 0 :(得分:0)

如果您只想显示数据,则实际上并不需要将所有内容都放入数组中。 SimpleXML使得处理XML数据变得非常简单。如果我可以建议一个可能不太复杂的解决方案:

<?php

function getFuelDataAsXml($make, $model)
{
  // In most cases CURL is overkill, unless you need something more complex
  $data = file_get_contents("https://www.fueleconomy.gov/ws/rest/ympg/shared/vehicles?make={$make}&model={$model}");

  // If we got some data, return it as XML, otherwise return null       
  return $data ? simplexml_load_string($data) : null;
}

// get the data for a specific make and model
$data = getFuelDataAsXml('honda', 'civic');

// iterate over all vehicle-nodes
foreach($data->vehicle as $vehicleData)
{
  echo $vehicleData->barrels08 . '<br />';
  echo $vehicleData->yourMpgVehicle->avgMpg . '<br />';
  echo '<hr />';
}

答案 1 :(得分:0)

要从DOM中获取数据,请使用Xpath:

$url = "https://www.fueleconomy.gov/ws/rest/ympg/shared/vehicles?make=honda&model=civic";

$dom = new DomDocument();
$dom->load($url);
$xpath = new DOMXpath($dom);

foreach ($$xpath->evaluate('/*/vehicle') as $vehicle) {
  var_dump(         
    array(
      $xpath->evaluate('string(fuelType)', $vehicle),
      $xpath->evaluate('number(fuelCost08)', $vehicle),
      $xpath->evaluate('number(barrels08)', $vehicle)
    )
  ); 
}

大多数Xpath表达式返回一个可以使用foreach迭代的节点列表。使用number()string()会将第一个节点的值或内容强制转换为浮点数或字符串。如果列表为空,您将获得一个空值。