0

わずかな変更を加えてコードに何度も表示されるこのブロックがあります。関数を使用したいのですが、関数を作成するときに知っている限り、引数の数を設定します。

使用しているコードのブロックは

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

主な違いは、xmlドキュメントをドリルダウンする最初の行は、他の場所ではさらにドリルダウンする可能性があることです。これは関数で実行できますか?

すなわち。いくつかの場所ではこのように見える必要があるかもしれません:

$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

引数の数が無限である必要はありません。これを行う方法は、関数を呼び出すたびに変化する可能性のある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 に答える