0

我有这个块,它在我的代码中一遍又一遍地出现,有细微的变化,我想使用一个函数,但据我所知,在编写函数时你设置了参数的数量,

我使用的代码块是

 $type = $xml->response->williamhill->class->type;
    $type_attrib = $type->attributes();
      echo "<h2>".$type_attrib['name']."</h2>";
      echo "<h2>".$type_attrib['url']."</h2>";

主要区别在于,通过 xml 文档向下钻取的第一行,它可能会在其他地方进一步向下钻取,这可能与函数有关吗?

IE。在某些地方可能需要看起来像这样:

$xml->response->williamhill->class->type->market->participant

4

2 回答 2

2

您可以使用 XPath:

function get_type_as_html($xml, $path)
{
  $type = $xml->xpath($path)[0]; // check first if node exists would be a good idea
  $type_attrib = $type->attributes();
  return "<h2>".$type_attrib['name']."</h2>" .
         "<h2>".$type_attrib['url']."</h2>";
}

用法:

echo get_type_as_html($xml, '/response/williamhill/class/type');

此外,如果此路径的任何部分始终相同,您可以将该部分移动到函数中,即

$type = $xml->xpath('/response/' . $path);
于 2013-01-23T22:46:28.617 回答
1

不需要无限数量的参数。做到这一点的方法是使用一个参数,每次调用该函数时该参数都会有所不同。

首先定义函数并将$type变量作为参数:

function output_header($type)
{
    $type_attrib = $type->attributes();
    echo "<h2>".$type_attrib['name']."</h2>";
    echo "<h2>".$type_attrib['url']."</h2>";
}

$xml->...然后,您可以使用您喜欢的任何属性调用该函数。

<?php
    output_header($xml->response->williamhill->class->type);
    output_header($xml->response->williamhill->class->type->market->participant);
?>
于 2013-01-23T22:36:31.883 回答