Home > Backend Development > PHP Tutorial > PHP抓取页面上的数组 并循环输出 急

PHP抓取页面上的数组 并循环输出 急

WBOY
Release: 2016-06-13 12:12:38
Original
1188 people have browsed it

PHP抓取页面上的数组 并循环输出 急 在线等
我用file_get_contents()抓取了 这个网址上的内容
http://simonfenci.sinaapp.com/index.php?key=simon&wd=1314abc

看似好像反回的是数组。。但是我不管怎么用foreach循环都报错。。

我只想把数组中的word里面的值 取出来。。谁帮帮我啊,急
------解决思路----------------------

$s = file_get_contents('http://simonfenci.sinaapp.com/index.php?key=simon&wd=1314abc');<br />preg_match_all('/\[word\] => (.+)/', $s, $m);<br />print_r($m[1]);
Copy after login
Array<br />(<br />    [0] => 1314<br />    [1] => abc<br />)<br /><br />
Copy after login

------解决思路----------------------
<br />$s=file_get_contents('http://simonfenci.sinaapp.com/index.php?key=simon&wd=1314abc');<br />$rule='#(?<=\[word\] =>)\s\w+#';<br />preg_match_all($rule,$s,$arr);<br />print_r($arr);<br />
Copy after login


<br />Array<br />(<br />    [0] => Array<br />        (<br />            [0] =>  1314<br />            [1] =>  abc<br />        )<br /><br />)<br />
Copy after login

------解决思路----------------------

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 ) ) "

//一个数组结构的字符串,而不是一个数组

//编码

<br />$arr = array(<br />    0=>array(<br />        'word '=> 1314,<br />        'word_tag'=> 90,<br />        'index' => 0<br />    ),<br />    1 => Array(<br />        'word' => 'abc',<br />        'word_tag' => 95,<br />        'index' => 1<br />    )<br />);<br />echo( json_encode($arr) );<br /><br />
Copy after login


//解码

<br />$arr    = array();<br />$url    = 'http://simonfenci.sinaapp.com/index.php?key=simon&wd=1314abc';<br />$ch     = curl_init();<br />curl_setopt($ch, CURLOPT_URL, $url);<br />curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);<br />curl_setopt($ch, CURLOPT_HEADER, 0);<br />$output = curl_exec($ch);<br />$arr    = json_decode($output,true);<br />curl_close($ch);<br />
Copy after login


也可以用 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); 输出的更短,并且可以轻易还原。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template