PHP在foreach循环中迭代simplexml [英] PHP Iterating simplexml in foreach loop

查看:156
本文介绍了PHP在foreach循环中迭代simplexml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个simplexml对象,如下所示:

 <?xml version =1.0?> 
< SalesInvoices xmlns:xsd =http://www.w3.org/2001/XMLSchemaxmlns:xsi =http://www.w3.org/2001/XMLSchema-instancexmlns = http://api.unleashedsoftware.com/version/1\">
< SalesInvoice>
< OrderNumber> 100< / OrderNumber>
< / SalesInvoice>
< SalesInvoice>
< OrderNumber> 101< / OrderNumber>
< / SalesInvoice>
< / SalesInvoices>

我想遍历它,只打印订单号。我使用这个脚本:

$ $ p $ $ $ $ $ $ $ $ foreach $ $回声你好;
echo $ salesinvoice-> OrderNumber;





$ b当我这样做的时候, 你好不打印。我做错了什么?

解决方案

<?php

$ string ='<?xml version =1.0?>
< SalesInvoices xmlns:xsd =http://www.w3.org/2001/XMLSchemaxmlns:xsi =http://www.w3.org/2001/XMLSchema-instancexmlns = http://api.unleashedsoftware.com/version/1\">
< SalesInvoice>
< OrderNumber> 100< / OrderNumber>
< / SalesInvoice>
< SalesInvoice>
< OrderNumber> 101< / OrderNumber>
< / SalesInvoice>
< / SalesInvoices>';
$ xml = simplexml_load_string($ string);

foreach($ xml as $ SalesInvoice){
print $ SalesInvoice-> OrderNumber;
}


I have a simplexml object which looks as below

<?xml version="1.0"?>
<SalesInvoices xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://api.unleashedsoftware.com/version/1">
    <SalesInvoice>
        <OrderNumber>100</OrderNumber>
    </SalesInvoice>
    <SalesInvoice>
        <OrderNumber>101</OrderNumber>
    </SalesInvoice>
</SalesInvoices>

I want to iterate through it and print only the order number. I use this script:

foreach ($xml->SalesInvoices->SalesInvoice as $salesinvoice) {
    echo "hello";
    echo $salesinvoice->OrderNumber;
}

When I do this I get no output from the loop at all, even the "hello" does not print. What am I doing wrong?

解决方案

Do

<?php

$string = '<?xml version="1.0"?>
<SalesInvoices xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://api.unleashedsoftware.com/version/1">
    <SalesInvoice>
        <OrderNumber>100</OrderNumber>
    </SalesInvoice>
    <SalesInvoice>
        <OrderNumber>101</OrderNumber>
    </SalesInvoice>
</SalesInvoices>';
$xml = simplexml_load_string($string);

foreach($xml as $SalesInvoice) {
    print $SalesInvoice->OrderNumber;
}

这篇关于PHP在foreach循环中迭代simplexml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆