2011-01-14 11 views
1
object(SimpleXMLElement)#1 (3) { 
["@attributes"]=> array(1) { 
    ["responsecode"]=> string(3) "200" 
} 
["nextpage"]=> object(SimpleXMLElement)#2 (0) { 
} 
["resultset_web"]=> object(SimpleXMLElement)#3 (2) { 
    ["@attributes"]=> array(4) { 
     ["count"]=> string(2) "10" 
     ["start"]=> string(1) "0" 
     ["totalhits"]=> string(8) "22497060" 
     ["deephits"]=> string(8) "23000000" 
    } 
    ["result"]=> array(10) { 
     [0]=> object(SimpleXMLElement)#4 (7) { 
     ["abstract"]=> string(110) "MSN's all-in-one Internet portal, the home of Hotmail, MSN Messenger, MSNBC News, Encarta, and Slate Magazine." 
     ["clickurl"]=> string(360) "http://teqpad.com/www/msn.com" 
     ["date"]=> string(10) "2011/01/14" 
     ["dispurl"]=> object(SimpleXMLElement)#14 (0) { 
     } 
     ["size"]=> string(5) "82136" 
     ["title"]=> string(3) "MSN" 
     ["url"]=> string(19) "http://www.msn.com/" 
     } 

私はPHPを使用してXML上からtitleabstractの値を抽出したいです。このxmlオブジェクトから値を抽出するにはどうすればよいですか?

+6

を。 –

+0

*(例)* http://de2.php.net/manual/en/simplexml.examples-basic.php – Gordon

+0

は、XMLがすでにSimpleXMLによって解析されているようです。 – badideas

答えて

1

あなたはすでにSimpleXMLでそれを解析していますが、本当にやりたいことはあなたのオブジェクトを横切って、titleabstractの値を見つけることです。

あなたのオブジェクトが$xmlある場合
$xml->resultset_web->result[0]->titleは一つの値についてtitleが含まれていながら、$xml->resultset_web->result[0]->abstractabstractが含まれています。すべての値については、

foreach ($xml->resultset_web->result as $v) { 
    $title = $v->title; 
    $abstract = $v->title; 
} 
+0

あなたはそれがsimplexml_load_stringによってロードされているのですが...残念ですが、私の間違いでした.. –

0

あなたはパスresultset_webですべてのノードを取得したい場合は - >結果 - >タイトル:

$xml = [your object]; 
$allTitlesAsArray = $xml->xpath('/resultset_web/result/title'); 
$allAbstractAsArray = $xml->xpath('/resultset_web/result/abstract'); 
0

テストされていないが、動作するはずです:

$ob->resultset_web->result[0]->title; 

として、言った、ちょうどPHPのsimplexmlのドキュメントを読んでください。そして、それぞれの場合が単純ではないことに注意してください。複数の結果がある場合、children()メソッドを使って子プロセスを反復する必要があります。上記のように直接アクセスすることはできません。

1

私はあなたがこのことから判断して抽出するために約10タイトルを持っていることを見ることができます:

["result"]=> array(10) { 

はこれを行う方法は次のようになります:varののvar_dumpのように見える

foreach ($simpleXML->resultset_web->result as $result) { 
    $title = $result->title; 
    $abstract = $result->abstract; 
} 
+0

私はそれがうまくいくとは思わない、あなたはchildren()メソッドを使用する必要があります$ simpleXML-> resultset_web-> result-> children())。 Simplexmlオブジェクトには予期しない動作があり、難しい方法を学びました。 – Naatan

+0

@Naatan:いいえ、これは動作します。 XMLは「 ... ...のようにフォーマットされています。 – netcoder

1

SimpleXMLオブジェクトを保持します。 それでは、あなたはこのような何かを持っているとしましょう:

//$data i a string containing your XML 
$xmlobj = new SimpleXMLElement($data); 

、あなたは、このような項目にアクセスすることができるはずです:まあ、まず...それはXMLではありません

foreach ($xmlobj->resultset_web->result as $result) { 
    echo $result->abstract; 
    echo $result->title; 
} 
関連する問題