【问题标题】:SimpleXML storing attributes in an arraySimpleXML 在数组中存储属性
【发布时间】:2016-08-19 11:49:27
【问题描述】:

我的代码有点工作,但我没有得到我想要的输出,我实际上只是想要输出“Gentle Breeze”,但我得到的是“SimpleXMLElement Object ([0] => Gentle Breeze)”

这是我的代码:

<head>
    <title>Open Weather API</title>
</head>

<body>
    <?php
    $url = "http://api.openweathermap.org/data/2.5/forecast/daily?q=London&mode=xml&units=metric&cnt=16&appid=Key";
    $xml = simplexml_load_file($url);

    foreach($xml->forecast->time as $times)
    {
        $windspeed[] = $times->windSpeed["name"];
    }

    print_r($windspeed[0])
?>
</body>

我尝试使用 echo 代替 print_r,但输出的都是“Array”

这是我从 API 中提取的 XML 示例:

<time day="2016-08-19">
  <symbol number="500" name="light rain" var="10d"/>
  <precipitation value="2.97" type="rain"/>
  <windDirection deg="188" code="S" name="South"/>
  <windSpeed mps="5.28" name="Gentle Breeze"/>
  <temperature day="22.58" min="17.06" max="22.58" night="18.39" eve="18.61" morn="17.06"/>
  <pressure unit="hPa" value="1012.32"/>
  <humidity value="72" unit="%"/>
  <clouds value="overcast clouds" all="92" unit="%"/>
</time>

我需要将它存储在一个数组中,以便稍后在我的代码中调用它,我只是将结果作为测试输出,以查看存储在数组中的内容,我只是希望它存储“Gentle Breeze " 不是 "SimpleXMLElement 对象 ([0] => 微风)"

【问题讨论】:

  • 看起来像多维数组,试试echo $windspeed[0][0]
  • 我试过了,好像没用

标签: php html xml simplexml openweathermap


【解决方案1】:

一个简单的字符串转换应该可以实现你想要的:

foreach($xml->forecast->time as $times)
{
    $windspeed[] = (string) $times->windSpeed["name"];
}

【讨论】:

    【解决方案2】:

    尝试这样做:

    $windspeed[] = $times->windSpeed->name;
    

    var_dump ($times->windSpeed->name);
    

    【讨论】:

    • 那不是将它存储在一个数组中?
    • 我更新了我的答案,但只是给你一个例子,看看该属性是否解析为类型字符串
    • 我需要使用 $windspeed[] = $times->windSpeed["name"];如果我只是输入 echo $xml->forecast->time->windSpeed["name"];我得到输出“Gentle Breeze”,所以我不明白为什么数组存储了不同的东西
    • @LukeRayner:那是因为通过 echo 输出会自动触发转换为字符串值。如果您想获得一个字符串值以在其他上下文中使用,而不是 require 字符串值,因此不会自动将其转换,您需要将其显式转换为字符串,请参阅我的回答.
    猜你喜欢
    • 2012-07-11
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    相关资源
    最近更新 更多