我的应用程序正在向服务器发送XML文件:需要一些关于编写PHP脚本来解析XML文件的指导

时间:2011-07-06 19:50:54

标签: php iphone xml

所以我的iPhone应用程序通过POST将XML文件中的购物车发送到URL。这是执行该操作的代码行

NSString *pathToSerializedCart = [rootPath stringByAppendingPathComponent:@"serializedCart.plist"];
NSString *shoppingCartString;
NSData *serializedData;
if (![fileManager fileExistsAtPath:pathToSerializedCart])
   {
    NSLog(@"ERROR:\nCouldnt find serialized cart in documents folder.");
    return;
   }


    serializedData = [NSData dataWithContentsOfFile:pathToSerializedCart];
    shoppingCartString = [[NSString alloc] initWithData:serializedData
                                                        encoding:NSUTF8StringEncoding];
    NSLog(@"%@", shoppingCartString);
    [shoppingCartString release];


    //==========================================================================


NSData *returnData = [NSURLConnection sendSynchronousRequest:request 
                                           returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] 
                          initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"%@",returnString);
[returnString release];

现在我喜欢做的是在文件welcome.php中的服务器上放置一个脚本,以便将此XML文件的内容回显给浏览器。

我看了很多例子,但他们都谈到了XML文件与服务器上的PHP文件存在于同一目录中的情况。我无法找到实际上是从应用程序中提取的PHP代码示例。

有人可以指出我正确的方向。

由于

1 个答案:

答案 0 :(得分:1)

更新看到您的完整objc后,我认为相关的POST值名称为userfile,并且我已更新下面的代码。

在PHP中,上传文件的文件名位置将位于$_FILES['userfile']['tmp_name']。建议var_dump($_FILES),以便您了解PHP如何处理上传的文件。

函数file_get_contents()将读取该临时文件名并将其内容作为字符串返回,您可以将其加载到DOMDocument中,如下面的最后一段代码所示。

推荐阅读:PHP docs on the $_FILES superglobal array

您需要从$_POST[]超全局检索XML数据,然后您可以使用simplexml_load_string()解析它。

// Sorry I'm unfamiliar with objC, so I can't glean the actual POST 
// value name from your code
// UPDATE misunderstood. the uploaded file is in $_FILES
// indexed by the POST key name.

// In development you can inspect your POST...
// To see the contents of your POST in PHP, do:
var_dump($_POST);
// Also check the contents of $_FILES
var_dump($_FILES);

// Your file is stored in the temp directory 
$xmlfile = $_FILES['userfile']['tmp_name'];

// Load it with SimpleXML
$xml = simplexml_load_file($xmlfile);

或者不是SimpleXML,我通常更喜欢更灵活的PHP DOMDocument库:

$xmlfile = $_FILES['userfile']['tmp_name'];
$dom = new DOMDocument();
$dom->loadXML(file_get_contents($xmlfile));

// Now parse it as necessary using DOM manipulators
$tags = $dom->getElementsByTagName("sometag");
foreach ($tags as $sometag) {
   // whatever...
}