donqo88682 2013-01-22 18:43
浏览 49
已采纳

通过在PHP中调用URL进行远程XML解析

I'm trying to parse xml data by calling url via file_get_contents() in php. The result is:

<?xml version="1.0" encoding="UTF-8" ?>
<RESPONSE>
<SINGLE>
<KEY name="sitename"><VALUE>RedCross Test</VALUE>
</KEY>
<KEY name="username"><VALUE>test1</VALUE>
</KEY>
<KEY name="firstname"><VALUE>Test1</VALUE>
</KEY>
<KEY name="lastname"><VALUE>testTest1</VALUE>
</KEY>
</SINGLE>
</RESPONSE>

Here is the procedure:

<?php

header('Content-type: text/html; charset=utf-8');

$xml_obj = file_get_contents("http://localhost/example/webservice/rest/server.php?wstoken=".$token."&function=get_info");

$data = $xml_obj->SINGLE->KEY[2]->VALUE;
echo $data;

?>

The response is: error on line 2 at column 1: Notice: Trying to get property of non-object on line 7. Could someone advise me?

  • 写回答

3条回答 默认 最新

  • douzi4724 2013-01-22 18:47
    关注

    The error is stating that $xml_obj is not an object. That's because it's not. It's simply a var storing the contents (as a string) of the response from file_get_contents.

    Instead of:

    $xml_obj = file_get_contents("http://localhost/example/webservice/rest/server.php?wstoken=".$token."&function=get_info");
    

    Try:

    $xml_obj = simplexml_load_file("http://localhost/example/webservice/rest/server.php?wstoken=".$token."&function=get_info");
    

    Or, if you need to use the contents for other stuff and want it in a separate variable:

    $contents = file_get_contents("http://localhost/example/webservice/rest/server.php?wstoken=".$token."&function=get_info");
    
    $xml = new DOMDocument();
    $xml->loadXML( $contents );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记