Heim > Backend-Entwicklung > PHP-Tutorial > PHP抓取页面上的数组 并循环输出 急 在线等

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Freigeben: 2016-06-23 13:42:39
Original
885 Leute haben es durchsucht

我用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]);
Nach dem Login kopieren
Array(    [0] => 1314    [1] => abc)
Nach dem Login kopieren

$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);
Nach dem Login kopieren


Array(    [0] => Array        (            [0] =>  1314            [1] =>  abc        ))
Nach dem Login kopieren

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) );
Nach dem Login kopieren


//解码

$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);
Nach dem Login kopieren


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

谢谢大家了,最后搞定了

Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage