【问题标题】:Pushing xml objects in to a array将 xml 对象推入数组
【发布时间】:2012-10-21 00:36:46
【问题描述】:

好吧,所以我对此有点困惑。我有一个看起来像这样的 xml:

<track>
<artist mbid="77cceea7-91bb-4a4c-ae41-bc9c46c1ccb5"> Red Hot Chili Peppers </artist>
<name> under the bridge </name>
<streamable>0</streamable>
<mbid/>
<album mbid="0fe94139-df63-4e51-b2e7-a1d53535cdd9">  Blood Sugar Sex Magik </album>
<url> http://xxxxxx.com </url>
<date uts="1351691244">31 Oct 2012, 13:47</date>
</track>

我使用 simpleXML 像这样解析 xml:

$artists = array();

$xml = simplexml_load_file("http://xxxxxxxxxxxxxx");

foreach($xml->recenttracks->track  as $track)
{
$artist = $track->artist;
    array_push($artists, $artist);
}  

var_dump($artists);

现在我希望得到一个看起来像这样的漂亮数组:

array(4) {
[0]=>
string(20) "Red Hot Chili Peppers "
[1]=>
string(20) "Red Hot Chili Peppers"
}

但我得到的是这样的:

array(2) 
{ 
[0]=> object(SimpleXMLElement)#6 (2) { ["@attributes"]=> array(1) { ["mbid"]=> string(36) "8bfac288-ccc5-448d-9573-c33ea2aa5c30" } [0]=> string(21) "Red Hot Chili Peppers" } 
[1]=> object(SimpleXMLElement)#4 (2) { ["@attributes"]=> array(1) { ["mbid"]=> string(36) "8bfac288-ccc5-448d-9573-c33ea2aa5c30" } [0]=> string(21) "Red Hot Chili Peppers" } 
} 

现在我如何只获得艺术家,而不是整个 SimpleXMLElement,因为我无法弄清楚。

【问题讨论】:

    标签: php xml arrays


    【解决方案1】:

    您要添加到数组中的项目是SimpleXMLElements。如果只想添加字符串值,则必须将SimpleXMLElement 强制转换为字符串。

    $artists = array();
    foreach($xml->recenttracks->track  as $track)
    {
        $artists[] = (string) $track->artist;
    }  
    
    var_export($artists);
    

    通常,当您需要字符串值时,您总是希望将SimpleXMLElement 转换为字符串。在某些情况下 PHP 会自动强制转换为字符串(例如当你 echo 它时),但是 PHP 类型强制规则非常复杂,最好始终明确。

    (另外,不需要array_push(),只需使用括号符号$arrayname[] = $appendedvalue。)

    【讨论】:

      【解决方案2】:

      var_dump 为您提供可用于访问不同部分的密钥,转换为字符串只会为您提供节点值,请尝试:

      $artist = (string) $track->artist[0];
      

      【讨论】:

        【解决方案3】:
        【解决方案4】:

        试试下面的代码。

        $xml = simplexml_load_file("artist.xml");
        
        echo $xml->artist;
        

        【讨论】:

        • 如果我只是回应艺术家,我只会得到艺术家的名字,但如果我将它推入数组,我会得到所有这些额外的信息。忘记在描述中提到了。
        • @user1593846 - 令人困惑的是您没有发布完整的 XML 文档,只有一个节点。请参阅我的答案以了解如何访问该值。
        猜你喜欢
        • 2017-12-05
        • 2023-03-14
        • 1970-01-01
        • 2016-05-09
        • 2011-02-13
        • 1970-01-01
        • 2023-03-29
        • 2019-03-24
        相关资源
        最近更新 更多