如何使用foreach函数打印XML数据

时间:2018-05-03 10:07:50

标签: xml laravel laravel-5 laravel-4 xml-parsing

如何在laravel 5.6函数中使用foreach打印XML数据请建议任何解决方案

这里附加了我的XML数据

<?xml version="1.0" encoding="utf-8"?> <interface-response> <tldlist> <tld> <tld>co.uk</tld> </tld> <tld> <tld>eu</tld> </tld> <tld> <tld>live</tld> </tld> <tld> <tld></tld> </tld> <tldcount>4</tldcount> </tldlist> <Command>GETTLDLIST</Command> <APIType>API</APIType> <Language>eng</Language> <ErrCount>0</ErrCount> <ResponseCount>0</ResponseCount> <MinPeriod></MinPeriod> <MaxPeriod>10</MaxPeriod> <Server>SJL1VWRESELL_T</Server> <Site>eNom</Site> <IsLockable></IsLockable> <IsRealTimeTLD></IsRealTimeTLD> <TimeDifference>+0.00</TimeDifference> <ExecTime>0.000</ExecTime> <Done>true</Done> <TrackingKey>20caefc5-035d-4a3d-8bbe-2743ea99ea8b</TrackingKey> <RequestDateTime>5/3/2018 3:02:01 AM</RequestDateTime> <debug><![CDATA[]]></debug> </interface-response>

请建议在我的刀片视图中打印XML数据的任何解决方案

1 个答案:

答案 0 :(得分:0)

我创建了Laravel包来简化对xml的解析:

https://github.com/mtownsend5512/xml-to-array

$xml = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<interface-response>
  <tldlist>
    <tld>
      <tld>co.uk</tld>
    </tld>
    <tld>
      <tld>eu</tld>
    </tld>
    <tld>
      <tld>live</tld>
    </tld>
    <tld>
      <tld></tld>
    </tld>
    <tldcount>4</tldcount>
  </tldlist>
  <Command>GETTLDLIST</Command>
  <APIType>API</APIType>
  <Language>eng</Language>
  <ErrCount>0</ErrCount>
  <ResponseCount>0</ResponseCount>
  <MinPeriod></MinPeriod>
  <MaxPeriod>10</MaxPeriod>
  <Server>SJL1VWRESELL_T</Server>
  <Site>eNom</Site>
  <IsLockable></IsLockable>
  <IsRealTimeTLD></IsRealTimeTLD>
  <TimeDifference>+0.00</TimeDifference>
  <ExecTime>0.000</ExecTime>
  <Done>true</Done>
  <TrackingKey>20caefc5-035d-4a3d-8bbe-2743ea99ea8b</TrackingKey>
  <RequestDateTime>5/3/2018 3:02:01 AM</RequestDateTime>
  <debug>
    <![CDATA[]]>
  </debug>
</interface-response>
XML;

有了它,您可以使用全局帮助器对其进行转换:

xml_to_array($xml);

或班级

// At the top of your controller:
use Mtownsend/XmlToArray/XmlToArray;

// Then in your code:
XmlToArray::convert($xml);

现在您将拥有一个数组:

array:18 [▼
  "tldlist" => array:2 [▼
    "tld" => array:4 [▼
      0 => array:1 [▼
        "tld" => "co.uk"
      ]
      1 => array:1 [▼
        "tld" => "eu"
      ]
      2 => array:1 [▼
        "tld" => "live"
      ]
      3 => array:1 [▼
        "tld" => []
      ]
    ]
    "tldcount" => "4"
  ]
  "Command" => "GETTLDLIST"
  "APIType" => "API"
  "Language" => "eng"
  "ErrCount" => "0"
  "ResponseCount" => "0"
  "MinPeriod" => []
  "MaxPeriod" => "10"
  "Server" => "SJL1VWRESELL_T"
  "Site" => "eNom"
  "IsLockable" => []
  "IsRealTimeTLD" => []
  "TimeDifference" => "+0.00"
  "ExecTime" => "0.000"
  "Done" => "true"
  "TrackingKey" => "20caefc5-035d-4a3d-8bbe-2743ea99ea8b"
  "RequestDateTime" => "5/3/2018 3:02:01 AM"
  "debug" => []
]

然后将转换后的xml发送到您的视图:

return view('your-view')->with(['xml' => $xml]);

然后循环遍历视图中所需的任何数据。