I am fairly new to iOS development and trying make a simple app which will communicate with PHP API. Data request and response will be in XML format only..
this is my php method for login,
function login()
{
$mainframe = JFactory::getApplication();
$xmlcnt = array();
if (!isset($HTTP_RAW_POST_DATA))
{
$HTTP_RAW_POST_DATA = file_get_contents("php://input");
}
if(empty($HTTP_RAW_POST_DATA))
{
$xmlcnt['code'] = "2";
return $xmlcnt;
}
$doc = new DOMDocument();
$doc->loadXML( $HTTP_RAW_POST_DATA);
$login_data = $doc->getElementsByTagName( "data" );
foreach( $login_data as $login )
{
$user_nm = $login->getElementsByTagName( "username" );
$user_nm = $user_nm->item(0)->nodeValue;
$password = $login->getElementsByTagName( "password" );
$password = $password->item(0)->nodeValue;
} ......
and the xmldata look like this "<data><username>testuser</username><password>password</password></data>"
i want to understand how/what should i use in xcode objective-c to send and recieve XML efficiently.
Thank you verymuch
you can check an XML parser for that, here some examples: http://cocoawithlove.com/2011/05/classes-for-fetching-and-parsing-xml-or.html
If you are asking which xml parser to use, Writing your own parser should help a lot in performance. We usually add data compression to keep size of data transfer low. We use simple zip library and also do encryption is needed. Zipping will help a lot if the data size is large
Related
I'm using DOMDocument with xpath to load some data to my site from external (fast) website.
Right now I use 4 urls (please see below). I need to increase to 8 urls.
What I have noticed, that the more of those you add, the more slower the site loads.
Is there any way to use xpath for more faster load?
Or maybe there's at least some kind of a way to load the data on website1 (child website) and when it loads, include the data to my main website.
Any tips would be appeciated.
<?php
$parent_title = get_the_title( $post->post_parent );
$html_string = file_get_contents('weburladresshere');
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($html_string);
libxml_clear_errors();
$xpath = new DOMXpath($dom);
$values = array();
$row = $xpath->query('myquery');
foreach($row as $value) {
print($value->nodeValue);
}
?>
It's slow because you load external sites. Instead of loading them just in time try to load them "in the background" via another php job and save them to a temporary file. Then you can load the html from your local temp file which is faster than the loading the remote $html_string via file_get_contents.
Extended answer
Here you can see a very leightweight example of how you could handle it.
function getPageContent($url) {
$filename = md5($url).'.tmp';
// implement your extended cache logic here
// for example: store it just for 60 seconds...
if(!file_exists($filename)) {
file_put_contents($filename, $url);
}
return file_get_contents($filename);
}
function businessLogic($url) {
$htmlContent = getPageContent($url);
// your business logic here
}
businessLogic($url);
I am trying to check and validate the phone number from an HTML page.
I am using the following code to check the phone number:
<?php
class Validation {
public $default_filters = array(
'phone' => array(
'regex'=>'/^\(?(\d{3})\)?[-\. ]?(\d{3})[-\. ]?(\d{4})$/',
'message' => 'is not a valid US phone number format.'
)
);
public $filter_list = array();
function Validation($filters=false) {
if(is_array($filters)) {
$this->filters = $filters;
} else {
$this->filters = array();
}
}
function validate($filter,$value) {
if(in_array($filter,$this->filters)) {
if(in_array('default_filter',$this->filters[$filter])) {
$f = $this->default_filters[$this->filters[$filter]['default_filter']];
if(in_array('message',$this->filters[$filter])) {
$f['message'] = $this->filters[$filter]['message'];
}
} else {
$f = $this->filters[$filter];
}
} else {
$f = $this->default_filters[$filter];
}
if(!preg_match($f['regex'],$value)) {
$ret = array();
$ret[$filter] = $f['message'];
return $ret;
}
return true;
}
}
This code is working fine for US phone number validation. But I do not understand how to pass a complete page to extract and check the valid phone number from an HTML page? Kindly help me and make me understand what I can do to fulfill my requirement.
You want to look into cURL.
cURL is a computer software project providing a library and command-line tool for transferring data using various protocols.
You should get the page from your php script (use cURL or whatever you want).
Find the div / input containing the telephone number from the response cURL give you. You can do that with a library like DomXPath (It allow you to navigate through DOM tree).
https://secure.php.net/manual/en/class.domxpath.php
Get the node values from the telephone input and pass it into your validator.
That is the way i would try it.
Your class does not really play any role in the task you want to accomplish because it's just some generic validation code that was never designed to become a scraper. However, the valuable part of it (the regular expression to determine what a US phone number is) is part of a public property so it can be reused in several ways (extend the class or call it from some other class):
public $default_filters = array(
'phone' => array(
'regex'=>'/^\(?(\d{3})\)?[-\. ]?(\d{3})[-\. ]?(\d{4})$/',
'message' => 'is not a valid US phone number format.'
)
);
E.g.:
// Scraper is a custom class written by you
$scraper = new Scraper('http://example.com');
$scraper->findByRegularExpression((new Validation())->default_filters['phone']['message']);
Of course, this is assuming that you cannot touch the validator code.
I cannot really answer the overall question without either writing a long tutorial or the app itself but here's some quick code to get started:
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTMLFile('http://example.com');
libxml_use_internal_errors(false);
$xpath = new DOMXPath($dom);
foreach ($xpath->query('//text()') as $textNode) {
var_dump($textNode->nodeValue);
}
I know the way to get all user media in instagram api with pagination. And we must request again with pagination url provided to get next photos.
I just wonder if i can save all of json api response include with next photos in pagination to one flat file for caching. The purpose is i can call all photos value from one file only, e.g: cache.json.
Is there a way to realize that in PHP Code if possible? Like using file_get and file_put function. Any help is appreciated so much :)
Here's my code, but need a tweak to fix it. Im using this wrapper https://github.com/cosenary/Instagram-PHP-API
require 'instagram.class.php';
$cache = './cache.json';
$instagram = new Instagram($accessToken);
$instagram->setAccessToken($accessToken);
$response = $instagram->getUserMedia($userID,$settings['count']);
do {
if($response){
file_put_contents($cache,json_encode($response)); //Save as json
}
} while ($response = $instagram->pagination($response));
echo 'finish';
With this code i getting the last pagination only. It seems the code overwrite the cache.json file, not adding.
Maybe you can suggest me how to fix it become adding, not overwriting.
-- Edit --
My code now working but not perfect, maybe you can try and fix it.
<?php
include('conf.php');
require 'instagram.class.php';
$cache = './cache_coba.json';
$instagram = new Instagram($accessToken);
$instagram->setAccessToken($accessToken);
$response = $instagram->getUserMedia($userID,$settings['count']);
while ($response = $instagram->pagination($response)) {
if($response){
$opn = file_get_contents($cache);
$opn .= json_encode($response);
file_put_contents($cache, $opn);
}
}
echo 'finish';
?>
i have a problem passing ByteArray from flash (as3) to amfphp to save an image.
With old version of amfphp, all worked in the past… now, with new version i have many problem.
I'm using version 2.0.1 and the first problem is that i have to do this, for access to my info:
function SaveAsJPEG($json)
{
$string = json_encode($json);
$obj = json_decode($string);
$compressed = $obj->{'compressed'};
}
in the past i wrote only:
function SaveAsJPEG($json)
{
$compressed = $json['compressed'];
}
Anyway… now i can take all data (if i use " $json['compressed']" i receive an error) but i can't receive my ByteArray data.
From flash i write this:
var tempObj:Object = new Object();
tempObj["jpgStream "]= createBitStream(myBitmmapData); // return ByteArray
tempObj["compressed"] = false;
tempObj["dir"] = linkToSave;
tempObj["name"] = this.imageName;
So.. in my php class i receive all correct info, except "jpgStream" that seems "null".
Do you have any idea?
I think you get 'null' because of json_encode/decode. Try using
$data = (array) $json;
$compressed = $data['compressed'];
This may help http://www.silexlabs.org/amfphp/documentation/data-types/
I have a bunch of PHP web services that construct JSON objects and deliver them using json_encode.
This works fine but I now have a requirement that the web services can also deliver in XML, depending on a given parameter.
I want to stay away from PEAR XML if possible, and hopefully find a simple solution that can be implemented with SimpleXML.
Can anyone give me any advice?
Thanks
You can create an associative array using json_decode($json,true) and try the following function to convert to xml.
function assocArrayToXML($root_element_name,$ar)
{
$xml = new SimpleXMLElement("<?xml version=\"1.0\"?><{$root_element_name}></{$root_element_name}>");
$f = function($f,$c,$a) {
foreach($a as $k=>$v) {
if(is_array($v)) {
$ch=$c->addChild($k);
$f($f,$ch,$v);
} else {
$c->addChild($k,$v);
}
}
};
$f($f,$xml,$ar);
return $xml->asXML();
}
// usage
$data = json_decode($json,true);
echo assocArrayToXML("root",$data);