0

Is it possible to store a PHP variable value in NSString?

getvariable.php

<?php
$variable = 6;
?>

Note: I am not interested in just using UIWebview to just visit getvariable.php and echo $getvariable. I need to store this variable in NSString.

How can I do it? is it through NSURLRequest, NSURLConnection??

2
  • 2
    PHP and Obj-C cannot simply "store" each other's variables. They need to communicate likely through an HTTP request. For that, you need to output the PHP variable, which then is simply text, which can be parsed and stored using Obj-C like any other HTTP response data. Commented Jun 18, 2012 at 7:00
  • That is right. I am parsing XML in my app too through http requests. I just need to know how to do this simple http request in order to get the value and store it in NSString. Commented Jun 18, 2012 at 7:15

2 Answers 2

1

I got it.

In variable.php

<?php
$var = 11;
echo $var;
?>

in my xcode class.m

NSString * url = [NSString stringWithFormat:@"http://website.com/variable.php"];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url ]];
NSString * serverOutput= [[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding];

NSLog(@"php variable is %@,serverOutput"); // it will print 11;
Sign up to request clarification or add additional context in comments.

1 Comment

I know this is a very old question, but I have a quick question. How would could I pass an NSString to a PHP variable?
0

You cannot pass variable from PHP to Objective c, or to any other client application for that matter, You will need to create a layer XML or RESTful interface to get that variable

For example you could update your php to the following (simple text, of JSON if you want)

<?php
echo ("Variable:6");
?>

Then in xCode do the following

NSString *strContent = [NSString stringWithContentsOfURL:@"YourUrl/getvariable.php"];
//Then get the var
NSString *strVariable = [strContent substringFromIndex:
               [strContent rangeOfString:@":"].location];

This is a simple synchronous text request, if you want you can change it to JSON and to asynchronous

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.