PHP解析json多个url

时间:2017-06-26 08:31:32

标签: php json

我想从多个url解析json。我可以使用以下代码解析网址:

<?php
$url1 = file_get_contents("http://www.url1.com");
$url2 = file_get_contents("http://www.url2.com");

$decode = json_decode($url1);

foreach( $decode as $obj1 ) {
    foreach( $obj1 as $obj2 ) {
        foreach( $obj2 as $obj3 ) {
          foreach( $obj3 as $obj4 ) {
            echo $obj4->name . '<br />';
          }
        }
    }
}
?>

我想解析url1和url2。我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

我认为您可以在解码array_merge()之后使用json

<?php
$url1 = file_get_contents("json1.json");
$url2 = file_get_contents("json2.json");

$decode1 = json_decode($url1);
$decode2 = json_decode($url2);
$decode_all = array_merge($decode1,$decode2);

foreach( $decode_all as $obj1 ) {
    echo $obj1->name . '<br />';
}
?>

<强>输出

Jaydeep
Manish

答案 1 :(得分:0)

  

Myjson1.json文件

{
            "name": "xyz",
            "city": "bla bla",
            "state": "bla bla bla"
}
  

Myjson2.json文件

{
            "country": "bla bla",
            "postal": "000000"
}
  

MyPhp.php文件

<?php

$url1 = "..\htdocs\myjson1.json";
$json1 = file_get_contents($url1);
$decode1 = json_decode($json1, TRUE);

$url2 = "..\htdocs\myjson2.json";
$json2 = file_get_contents($url2);
$decode2 = json_decode($json2, TRUE);

print '<pre>';
print_r($decode1);
print_r($decode2);
print '<pre> <hr>';

$merge_array = array_merge($decode1,$decode2);

print_r($merge_array);

//http://php.net/manual/en/function.extract.php
extract($merge_array, EXTR_PREFIX_SAME, "wddx"); 


echo "<h1> $name </h1>";
echo "<h1> $city <h1>";
echo "<h1> $state <h1>";
echo "<h1> $country <h1>";
echo "<h1> $postal <h1>";

?>

输出:

enter image description here

注意: wddx_deserialize参考http://php.net/manual/en/function.extract.php

  

或(第二路)

<?php

    $decode1 = array("name"=>"xyz","city"=>"bla bla");
    $decode2 = array("state"=>"xyz","country"=>"India");

    $merge_array = array_merge($decode1,$decode2);

    foreach($merge_array as $mydata) {

         echo '<h2>'. $mydata .'</h2>';
    }

?>

演示:https://eval.in/822392