【问题标题】:PHP - Echo key value of the array itemsPHP - 数组项的回显键值
【发布时间】:2011-05-12 22:58:11
【问题描述】:

我需要回显一个数组的键值。

这就是我输出数组的方式:

foreach($xml->channel->item as $item) {
  $item->title
}

我已经尝试添加:

foreach($xml->channel->item as $key => $item)

但我回显的值是:item

有什么想法吗?

项目结果的变量转储:

var_dump($xml->channel->item);

    object(SimpleXMLElement)#4 (5) { 
["title"]=>  string(33) "BA and union agree to end dispute" 
["description"]=>  string(118) "British Airways and the Unite union reach an agreement which could end the long-running dispute between the two sides." 
["link"]=>  string(61) "http://www.bbc.co.uk/go/rss/int/news/-/news/business-13373638" 
["guid"]=>  string(43) "http://www.bbc.co.uk/news/business-13373638" 
["pubDate"]=>  string(29) "Thu, 12 May 2011 12:33:38 GMT" 
} 

【问题讨论】:

  • 你把echo放在$item->title前面了吗?尝试var_dump($xml->channel->item 并调试它是否已经是array
  • 我认为它是一个 SimpleXML 对象,不一定会作为数组转储

标签: php


【解决方案1】:

尝试做:

$data = $xml->channel->item;

if (is_object($data) === true)
{
    $data = get_object_vars($data);
}

echo '<pre>';
print_r(array_keys($data));
echo '</pre>';

【讨论】:

  • 这给了我项目下每个条目的密钥:
  • @CLiown:你不想这样吗? foreach (array_keys($data) as $key) { echo $key; }.
【解决方案2】:

它不是一个数组,而是一个 SimpleXMLElement。所以循环遍历子节点并输出名称。

foreach ( $xml->channel->item->children() as $child ) {
  echo $child->getName();
}

【讨论】:

    【解决方案3】:

    foreach($xml->channel->item as $key => $item) 回声$键; }

    添加:

    在此处查看答案以将其转换为数组Trouble traversing XML Object in foreach($object as $key => $value);

    【讨论】:

    • @CLiown 那是因为它不是一个真正的数组。它是一个 SimpleXMLElement,它模仿一个没有真正索引的数组,只有很多值。
    【解决方案4】:

    您好,也许您可​​以尝试将 XML 转换为 Array

    function xml2array ( $xmlObject, $out = array () )
    {
            foreach ( (array) $xmlObject as $index => $node )
                $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;
    
            return $out;
    }
    

    然后用 foreach 访问它。

    示例

    $x = new SimpleXMLElement(<<<EOXML
    <root>
       <node>Some Text</node>
    </root>
    EOXML
    );
    
    xml2array($x,&$out);
    var_dump($out);
    

    输出

    array(1) {
      ["node"]=>
      string(9) "Some Text"
    }
    

    【讨论】:

    • 这只是一个简单的递归方法,解析器所有的XML节点。试试xml2array($xml, $out) 然后foreach($out as $key=&gt;$value){}
    • 当我 var_dump($out) 时结果为 NULL
    • 哎呀,错了。 $out 引用,xml2array($xml, &amp;$out)
    猜你喜欢
    • 2019-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 2014-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多