1

更新:配列としてキャストするとうまくいきます。私は賛成票を投じるのに十分な影響力を持っていないので、この応答を参照してください:)

私はこの問題を多くの潜在的な原因から始めましたが、多くの診断を行った後でも問題は解決せず、明確な答えはありません。

この API が読み込まれた XML ファイルの最初のタグの下の最初のタグの下の最初のタグにある地名 "Gaborone" を出力したいと考えています。これを解析してそのコンテンツを返すにはどうすればよいですか?

    <?php

      # load the XML file
      $test1 = (string)file_get_contents('http://www.afdb.org/fileadmin/uploads/afdb/Documents/Generic-Documents/IATIBotswanaData.xml');

      #throw it into simplexml for parsing      
      $xmlfile = simplexml_load_string($test1);

      #output the parsed text
      echo $xmlfile->iati-activity[0]->location[0]->gazetteer-entry;

    ?>

これを返すのに失敗することはありません:

Parse error: syntax error, unexpected '[', expecting ',' or ';'

タグ名にハイフンが含まれないように構文を変更してみました。

echo $xmlfile["iati-activity"][0]["location"][0]["gazetteer-entry"];

. . . しかし、それは完全な無を返します。エラーなし、ソースなし。

これら 以外の場合は役立つ スレッドに基づいてデバッグも試みましたが、解決策はどれも機能しませんでした。simplexml のアドレス指定に明らかなエラーがありますか?

4

2 に答える 2

1

タグ名にハイフンが含まれないように構文を変更してみました: echo $xmlfile["iati-activity"][0]["location"][0]["gazetteer-entry"];

ここでの問題は、配列へのオブジェクトのネイティブキャストが再帰的ではないため、主キーに対してのみそれを行ったことです。はい、あなたの推測は正しいです-simplexml_load_string()構文の問題のため、戻り値を操作するときにオブジェクトのプロパティを処理するべきではありません。代わりに、その戻り値 ( stdclass) を再帰的に配列にキャストする必要があります。そのためにこの関数を使用できます。

  function object2array($object) { 
    return json_decode(json_encode($object), true); 
  } 

残り:

  // load the XML file
  $test1 = file_get_contents('http://www.afdb.org/fileadmin/uploads/afdb/Documents/Generic-Documents/IATIBotswanaData.xml');

  $xml = simplexml_load_string($test1);

  // Cast an object into array, that makes it much easier to work with
  $data = object2array($xml);

  $data = $data['iati-activity'][0]['location'][0]['gazetteer-entry']; // Works

  var_dump($data); // string(8) "Gaborone"
于 2013-09-23T03:33:50.890 に答える
0

次の文字列置換を行うまで、simpleXML コマンドを使用して XML を解析する際に同様の問題が発生しました。

//$response contains the XML string
$response = str_replace(array("\n", "\r", "\t"), '', $response); //eliminate newlines, carriage returns and tabs
$response = trim(str_replace('"', "'", $response)); // turn double quotes into single quotes
$simpleXml = simplexml_load_string($response);
$json = json_decode(json_encode($simpleXml)); // an extra step I took so I got it into a nice object that is easy to parse and navigate

それがうまくいかない場合、CDATA が常に適切に処理されないという PHP での議論があります- PHP のバージョンに依存します。

simplexml_load_string 関数を呼び出す前に、次のコードを試すことができます。

if(strpos($content, '<![CDATA[')) {
   function parseCDATA($data) {
      return htmlentities($data[1]);
   }
   $content = preg_replace_callback(
      '#<!\[CDATA\[(.*)\]\]>#',
      'parseCDATA',
      str_replace("\n", " ", $content)
   );
}

これを読み直しましたが、最後の行でエラーが発生していると思います-これを試してください:

echo $xmlfile->{'iati-activity'}[0]->location[0]->{'gazetteer-entry'};

于 2013-09-23T00:13:11.297 に答える