在 php 中加载 xml 并返回数据


Load the xml in php and return the data

我正在寻找如何在PHP中加载XML文件并返回数据而不是重定向。最好尽可能向最终用户隐藏 xml 内容。

我见过这样的东西,但我无法让它工作,请问您是否可以用链接示例写出完整的代码。.

     public function sendResponse($type,$cause) {
    $response = '<?xml version="1.0" encoding="utf-8"?>';
    $response .= '<response><status>'.$type.'</status>';
            $response = $response.'<remarks>'.$cause.'</remarks></response>';
            return $response;
 }
 ....
 ....
 header("Content-type: text/xml; charset=utf-8");
 echo sendResponse($type,$cause);

如果可以的话,请帮忙。提前感谢,SX

我不确定是否理解您的请求,但首先您不能调用 sendResponse(),因为它不是一个函数,而是类中的一个方法

您需要实例化您的类,然后调用该方法。

例:

$yourObject = new YourClass();
$yourObject->sendResponse();

查看手册

对于您的情况,请参阅simpleXML手册并尝试:

    function sendResponse($type,$cause) {
    $response = '<?xml version="1.0" encoding="utf-8"?>';
    $response .= '<response><status>'.$type.'</status>';
            $response = $response.'<remarks>'.$cause.'</remarks></response>';
            return $response;
 }
$type="type";
$cause="cause";
var_dump(simplexml_load_string(sendResponse($type,$cause)));

如果您的脚本是外部的,您可以使用 file_get_contents

$xml = file_get_contents('http://yourTarget.com');
var_dump($xml);

你的问题在某种程度上误导了我,确保如果你想加载一个外部 xml 文件并让你的 PHP 代码解析它。尝试以下代码

Assume the following is your xml content fo text.xml 
<?xml version='1.0' encoding='UTF-8'?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>"
<-- PHP -->
$file = 'http://exmp.com/text.xml';     // give the path of the external xml file
if(!$xml = simplexml_load_file($file))    // this checks whether the file exists
exit('Failed to open '.$file);           // exit when the path is wrong 
print_r($xml);                          // prints the xml format in the form of array 

你的输出将是这个

SimpleXMLElement Object ( 
[to] => Tove 
[from] => Jani 
[heading] => Reminder 
[body] => Dont forget me this weekend!
 ) 

希望这有帮助...