PHP 调用返回 XML/JSON 的 url


PHP call a url returning XML/JSON

我是PHP的绝对初学者。很抱歉有一个非常基本的 API 问题。我在编码时陷入困境,我需要调用一个 URL,这将返回 XML 或 JSON。现在我必须在变量中捕获它。

例如,我编写了以下代码:

class Search {
   private $documents = array();
   public function __construct() {
      $xmlDoc = new DOMDocument();
      $xmlDoc->load("solr.xml");
      .....

现在我直接加载一个 XML。我不想这样做,相反:

Step1:我想调用一个http url,它向我返回XML或JSON。
步骤2:我需要将其存储在一些变量中,例如上面的
xmlDocStep3:稍后我当然想解析它。

我对步骤 3 没有任何问题,但我只需要一些关于如何完成步骤 1 和 2 的指示或帮助?

load应该接受URL作为参数。

$xmlDoc = new DOMDocument();
$xmlDoc->load('http://example.com/path/to/file.xml');

或者,您可以使用 file_get_contents 将 URL 下载到字符串。

$xml = file_get_contents('http://example.com/path/to/file.xml');
$xmlDoc = new DOMDocument();
$xmlDoc->loadXML($xml);

或者对于 JSON:

$json = json_decode(file_get_contents('http://example.com/path/to/file.json'));

要使用 Json 执行此操作,您首先需要一个包含一些 json 变量的页面。

  1. 您可以通过键入以下内容自行执行此操作:

    $jsonVar = array('var1','var2'); // several variables
    echo encode_json($jsonVar);
    
  2. 您可以通过键入以下内容来访问这些变量:

    $jsonUrl = 'http://example.com/json.php';
    $jsonUrl = json_decode(file_get_contents($jsonUrl));
    
  3. 要显示这些变量之一,您可以键入:

    echo $jsonUrl[1]; // you can use print_r($jsonUrl); //for displaying the right array numbers to access the vars