Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 多次深入查看xml提要的有效方法_Php_Xml_Function - Fatal编程技术网

Php 多次深入查看xml提要的有效方法

Php 多次深入查看xml提要的有效方法,php,xml,function,Php,Xml,Function,我发现自己深入研究了xml提要,它们几乎是相同的提要,除了几个数组名 理想情况下,我想做一种我可以调用的函数,但我不知道如何使用这种数据 //DRILLING DOWN TO THE PRICE ATTRIBUTE FOR EACH FEED & MAKING IT A WORKING VAR $wh_odds = $wh_xml->response->will->class->type->market->participant; $wh_od

我发现自己深入研究了xml提要,它们几乎是相同的提要,除了几个数组名

理想情况下,我想做一种我可以调用的函数,但我不知道如何使用这种数据

//DRILLING DOWN TO THE PRICE ATTRIBUTE FOR EACH FEED & MAKING IT A WORKING VAR
  $wh_odds = $wh_xml->response->will->class->type->market->participant;
  $wh_odds_attrib = $wh_odds->attributes();
  $wh_odds_attrib['odds'];


  $lad_odds = $lad_xml->response->lad->class->type->market->participant;
  $lad_odds_attrib = $lad_odds->attributes();
  $lad_odds_attrib['odds'];

正如您所见,它们本质上非常相似,但我不太确定如何简化设置工作变量的过程,而不必每次写3行。

您可以这样做:

 function getAttrib ($xmlObj, $attrName) {
      $wh_odds = $xmlObj->response->$attrName->class->type->market->participant;
      $wh_odds_attrib = $wh_odds->attributes();
      return $wh_odds_attrib['odds'];
}

getAttrib ($wh_xml, "will");

希望对您有所帮助。

您可能正在寻找的函数已被调用

当然,它是自己设计的,用于从XML文件中提取内容。在您的例子中,获取所有这些元素的
赔率
属性的xpath表达式是:

response/*/class/type/market/participant/@odds
您还可以将
*
替换为具体的元素名称,或者在其中允许多个名称,等等

$odds = $lad_xml->xpath('response/*/class/type/market/participant/@odds');
与您的代码不同,它在数组中包含所有属性元素(在变量中包含属性的父元素)。一个示例结果(考虑其中两个因素)是:

Array
(
    [0] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [odds] => a
                )

        )

    [1] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [odds] => a
                )

        )

)
您也可以轻松地将其转换为字符串:

$odds_strings = array_map('strval', $odds);

print_r($odds_strings);

Array
(
    [0] => a
    [1] => a
)
如果您想获得所有
参与者
元素的
几率
属性,Xpath尤其有用:

//participant/@odds
您不需要显式指定每个父元素名称

我希望这是有帮助的