我用file_get_contents()抓取了 這個網址上的內容
http://simonfenci.sinaapp.com/index.php?key=simon&wd=1314abc
看似好像反回的是數組。。但是我不管怎麼用foreach迴圈都報錯。。
我只想把數組中的word裡面的值 取出來。。誰幫幫我啊,急
回複討論(解決方案)
你這個得到的是一個字串 。所以肯定不用foreach .
得到word裡面值 正則或者其他的方法吧 。
$s = file_get_contents('http://simonfenci.sinaapp.com/index.php?key=simon&wd=1314abc');preg_match_all('/\[word\] => (.+)/', $s, $m);print_r($m[1]);
Array( [0] => 1314 [1] => abc)
$s=file_get_contents('http://simonfenci.sinaapp.com/index.php?key=simon&wd=1314abc');$rule='#(?<=\[word\] =>)\s\w+#';preg_match_all($rule,$s,$arr);print_r($arr);
Array( [0] => Array ( [0] => 1314 [1] => abc ))
file_get_contents()抓取頁面返回的是一個字串。
如果需要通過遠程介面調用,建議 http://simonfenci.sinaapp.com/index.php?key=simon&wd=1314abc 的輸出可以更改為json格式的字串。
在調用處擷取到內容的時候使用json_decode進行解碼就能得到php數組了。
另外,不建議使用file_get_contents擷取遠程網頁的內容,推薦使用curl。
http://simonfenci.sinaapp.com/index.php?key=simon&wd=1314abc
返回的是:
string(247) "Array ( [0] => Array ( [word] => 1314 [word_tag] => 90 [index] => 0 ) [1] => Array ( [word] => abc [word_tag] => 95 [index] => 1 ) ) "
//一個數組結構的字串,而不是一個數組
//編碼
$arr = array( 0=>array( 'word '=> 1314, 'word_tag'=> 90, 'index' => 0 ), 1 => Array( 'word' => 'abc', 'word_tag' => 95, 'index' => 1 ));echo( json_encode($arr) );
//解碼
$arr = array();$url = 'http://simonfenci.sinaapp.com/index.php?key=simon&wd=1314abc';$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt($ch, CURLOPT_HEADER, 0);$output = curl_exec($ch);$arr = json_decode($output,true);curl_close($ch);
也可以用 serialize() 和 unserialize() 這個序列化函數, 替換 json。
補充:
//json 返回的字串
[{"word ":1314,"word_tag":90,"index":0},{"word":"abc","word_tag":95,"index":1}]
//serialize 返回的字串
a:2:{i:0;a:3:{s:5:"word ";i:1314;s:8:"word_tag";i:90;s:5:"index";i:0;}i:1;a:3:{s:4:"word";s:3:"abc";s:8:"word_tag";i:95;s:5:"index";i:1;}}
明顯比直接 var_export($val,true); 輸出的更短,並且可以輕易還原。
謝謝大家了,最後搞定了