PHP抓取頁面上的數組 並迴圈輸出 急 線上等

來源:互聯網
上載者:User
我用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); 輸出的更短,並且可以輕易還原。

謝謝大家了,最後搞定了

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.