simplexml_load_string获取属性

时间:2016-02-12 00:17:36

标签: php xml simplexml

如何将name或name1变量设置为$ event的name属性的值?当我单步执行代码名称等于没有值的simplexmlobject时,name2为null。

$ name3 = $ event-> attributes() - > name;也不起作用。

我对如何正确使用它感到困惑。

$curl = curl_init();

curl_setopt_array($curl, Array(
    CURLOPT_URL            => 'http://odds.smarkets.com/oddsfeed.xml',
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_ENCODING       => 'UTF-8'
 ));

$data = curl_exec($curl);
curl_close($curl);

$xml = simplexml_load_string($data);
$football = array();
foreach($xml->event as $event){
if($event->attributes()->type == "Football match"){
    $att = $event->attributes();
    $name = $att['name'];
    $name2 = $att->attributes()->name;
    $name3 = $event->attributes()->name;
    $football[] = $event;
}
}

foreach($football as $game){
   if($game->attributes()->name == "Sunderland vs. Manchester United"){
     $a = $game;
   }
 }

2 个答案:

答案 0 :(得分:0)

一些脚本可以运行,它可以获得游戏Sunderland。没有意义的部分如下:

$att = $event->attributes(); // gets all the attributes
// using `$att` then invokes the attributes method
$name2 = $att->attributes()->name;

您不需要使用->attributes而不是$att它已具有属性。

如果你想搜索那个Sunderland游戏,只需删除一些不需要的部分:

$xml = simplexml_load_string($data);
$football = array();
foreach($xml->event as $event){
    if($event->attributes()->type == "Football match"){
        $football[] = $event; // push foot ball matches
    }
}

foreach($football as $game){
    // search for sunderland game
    if($game->attributes()->name == "Sunderland vs. Manchester United"){
        $a = $game;
    }
}

print_r($a); // checker

如果您真的想将该特定名称分配到变量中,只需将该属性强制转换为(string),ala:

$name = (string) $event->attributes()->name;

修改 如果需要,只需使用foreach转到适当的级别。只需添加is_array即可进行一些检查。有些级别的价格平稳。有些优惠有些优惠。做相应的检查。为了让你前进,这是一个例子:

$match = 'Sunderland vs. Manchester United';
foreach($football as $game){
    if($game->attributes()->name == $match){
        // if that game is found
        foreach($game->market as $market) {

            foreach($market->contract as $contract) {

                // offers
                if(!empty($contract->offers)) {
                    foreach($contract->offers->price as $price) {
                        // single level price
                        if(!is_array($price)) {
                            $decimal = (string) $price->attributes()->decimal;
                            echo $decimal;
                        }
                        // multi leveled price
                        else {
                            foreach($price as $p) {
                                $decimal = (string) $p->attributes()->decimal;
                                echo $decimal;
                            }
                        }


                    }
                }
                // end offers

            }

        }

    }
}

概念仍然相同,在需要时对属性使用类型转换。这应该让你去。

答案 1 :(得分:0)

SimpleXML提供__toString()方法来返回字符串值:

$name = $event->attributes()->name->__toString();