simplexml_load_string 获取属性

simplexml_load_string getting attributes

如何将 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;
   }
 }

一些脚本有效,它会获得游戏 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

            }

        }

    }
}

概念还是一样的,在需要的时候对属性使用类型转换。这应该让你继续。

SimpleXML 为 return 字符串值提供 __toString() 方法:

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