0

Recently I got from here about how to parse large xml files using of XMLReader and SimpleXML in PHP. I tried to adapt the code of above mentioned tutorial into my php procedure like this:

$xml_url = "http://localhost/rest/server.php?wstoken=".$token&function=contents";
    $reader = new XMLReader;
    $reader->open($xml_url);

    while($reader->read()){
        if($reader->nodeType == XMLReader::ELEMENT && $reader->name == 'SINGLE'){
            $doc = new DOMDocument('1.0','UTF-8');
            $xml = simplexml_import_dom($doc->importNode($reader->expand(), true));
            //$titleString = (string) $xml->description;
            echo $xml->description;
        }
    }

The XML file called via url is so (the xml version is here): screenshot

Other SINGLE tags (marked with 'red') have the same structure and I want to print 'description' of them also.

The output is with above mentioned php procedure is: error on line 1 at column 1: Extra content at the end of the document. Any help would be great.

4

1 に答える 1

1

SimpleXML関数で十分なはずです:

$xml=simplexml_load_file('http://dl.dropbox.com/u/72519118/response.xml');
var_dump($xml->xpath('//SINGLE/KEY[@name="description"]/VALUE/text()'));

上記のvar_dump出力:

array(3) {
  [0]=>
  object(SimpleXMLElement)#2 (1) {
    [0]=>
    string(1703) "<div class="no-overflow">..."
  }
  [1]=>
  object(SimpleXMLElement)#3 (1) {
    [0]=>
    string(9906) "<div class="no-overflow">..."
  }
  [2]=>
  object(SimpleXMLElement)#4 (1) {
    [0]=>
    string(4114) "<div class="no-overflow">..."
  }
}

のタグ名xpath()は大文字と小文字が区別されるため、'//single/key...'機能しないことに注意してください。

追加

SimpleXML でテキスト値を取得する「標準的な」方法は次のとおりです$KEY->VALUE

ただし、XML ツリーの「終了」ノードに到達した場合 (XPath で行ったように)、単純に文字列に型キャストして値を取得できます。

$xml=simplexml_load_file('http://dl.dropbox.com/u/72519118/response.xml');
$result=$xml->xpath('//SINGLE/KEY[@name="description"]/VALUE/text()');
foreach($result as $text)
{
    var_dump((string)$text);
}

上記の出力:

string(1703) "<div class="no-overflow"><p>..."
string(9906) "<div class="no-overflow"><h3>..."
string(4114) "<div class="no-overflow"><h3>..."
于 2013-01-23T03:48:30.830 に答える