如何在多维数组中提取第二级元素

时间:2017-02-05 01:00:59

标签: php xml multidimensional-array

这是来自WA州DOR网站的xml。

<?xml version="1.0" encoding="UTF-8"?>
<response loccode="3406" localrate="0.024" rate="0.089" code="0">
<addressline houselow="6500" househigh="6598" evenodd="E" street="LINDERSON WAY SW" state="WA" zip="98501" plus4="6561" period="Q12017" code="3406" rta="N" ptba="Thurston PTBA" cez=""/>
<rate name="TUMWATER" code="3406" staterate="0.065" localrate="0.024"/></response>

我已使用PHP命令'simplexml_load_string';

将其转换为数组
SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [loccode] => 1726
            [localrate] => 0.031
            [rate] => 0.096
            [code] => 0
        )
    [addressline] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [houselow] => 5201
                    [househigh] => 5299
                    [evenodd] => O
                    [street] => 37TH AVE S
                    [state] => WA
                    [zip] => 98118
                    [plus4] => 6115
                    [period] => Q12017
                    [code] => 1726
                    [rta] => Y
                    [ptba] => King PTBA
                    [cez] => Duwamish
                )
        )
    [rate] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [name] => SEATTLE
                    [code] => 1726
                    [staterate] => 0.065
                    [localrate] => 0.031
                )
        )
)

我已经能够从第一级拉出两个元素,我需要一个元素从第二级开始。我在这个上搜索并测试了6个多小时。我需要帮助从数组或xml中提取'plus4'值。 这是我到目前为止的尝试:

<?php
$addr1 = "5211 37th Ave S";
`enter code here`$city = "seattle";
$zip = "98118";
$postdata = array("output"=>"xml", "addr"=>urlencode($addr1), "city"=>urlencode($city), "zip"=>$zip);
$url = "http://dor.wa.gov/AddressRates.aspx";
error_reporting(E_ALL);
ini_set('display_errors', 1);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST , 1);
curl_setopt($ch, CURLOPT_POSTFIELDS , $postdata);
$return = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($return === FALSE) {
echo "cURL Error: " . curl_error($ch); }
curl_close($ch);
$xml=simplexml_load_string($return) or die("Error: Cannot create object");

echo "Localation Code: " . $xml['loccode'];
echo "<br>Tax Rate: " . $xml['rate'];

echo "<br>" . $xml[1]['plus4'];
?>

2 个答案:

答案 0 :(得分:0)

也许将嵌套数据转换为一维数组?

这个问题看起来很相似: How to Flatten a Multidimensional Array?

答案 1 :(得分:0)

试试这个$ xml-&gt;地址线['plus4']。 XML是一个对象。