Convert String back into an array PHP - php

I have two different torrent scrapping classes and I want to combine them, they are working fine separately but the only problem is, when I convert my string into an array, it does not work.
That's the codes I am using so far.
<?php
require 'scraper.php';
require 'tor-info.php';
$scraper = new Scrapeer\Scraper();
$torrent = new Torrent( './test.torrent' );
$hashix = $torrent->hash_info();
var_dump($torrent->scrape()); // shows trackers list like this array(21) { ["udp://tracker4.piratux.com:6969/announce"]=> bool(false) ["udp://tracker.trackerfix.com:80/announce"]=> bool(false) ["udp://tracker.pomf.se:80/announce"]=> bool(false) ["udp://torrent.gresille.org:80/announce"]=> bool(false) so on..
$trackers = array( "udp://tracker4.piratux.com:6969/announce", "udp://tracker.trackerfix.com:80/announce", "udp://tracker.pomf.se:80/announce" ); // now here we need that trackers list
$hash = array( $hashix );
$info = $scraper->scrape( $hash, $trackers );
//print_r( $info );
echo '<br><hr>';
foreach ($info as $key => $value) {
echo 'SEEDS :' .$value['seeders'].'<br />';
echo 'LEECHES :' .$value['leechers'].'<br />';
}
?>
In the first part I converted the array into String to get the readable result, and then in the second part I needed to convert that string back into single array to produce the result.

Why don't you just make them an array to begin with?
<?php
require 'scraper.php';
require 'tor-info.php';
$scraper = new Scrapeer\Scraper();
$torrent = new Torrent( './test.torrent' );
$hashix = $torrent->hash_info();
$trackers = array_keys($torrent->scrape());
$hash = array( $hashix );
$info = $scraper->scrape( $hash, $trackers );
echo '<br><hr>';
foreach ($info as $key => $value) {
echo 'SEEDS :' .$value['seeders'].'<br />';
echo 'LEECHES :' .$value['leechers'].'<br />';
}

Since your string looks like this (from comment) : "udp://tracker4.piratux.com:6969/announce","udp://tracker.trackerfix.com:80/announce" you could use PHP's explode() function like so:
$recombined = explode(',', str_replace('"', '', $trackers));

Related

Array element returning "true" instead of value

I have a PHP code that converts a JSON into an array of two elements.
{"object":"card","id":"card_1"}
But when I try to print the both, the first returns the value and the second only the boolean.
echo 'id = ' . $response["id"];
echo 'object = ' .$response["object"];
Getting this:
id = true
object = card
What is wrong?
It seems, that you use json_decode to convert your JSON data to an array. Use next basic example to get your expected data:
<?php
// Input
$json = '{"object":"card","id":"card_1"}';
$array = json_decode($json, true);
// Specific items
echo 'id = '.$array["id"].'<br>';
echo 'object = '.$array["object"].'<br>';
// All items
foreach($array as $key => $value) {
echo $key.": ".$value."<br>";
}
?>
Could you please provide the code you use to convert this JSON into an array ?
This works fine:
$jsonObject = '{"object":"card","id":"card_1"}';
$decodedObject = json_decode($jsonObject);
$object = $decodedObject->object;
$id = $decodedObject->id;
echo "Object: {$object}, ID: {$id}";

php file that returns a string json encode didnt work

I have an php file that gives me the response i need as a string, i need it to be an array encoded in json, im not that good with php, can any one help ?
this is how it works fine as a string
- printf("user: \"%s\" \"%s\" email: \"%s\" \n", $row['firstname'], $row['lastname'],$row['email']);
But i need it as an array in json that is how i tried to do it
-array_push($mynewArray,array("firstname \%s"=>$row['firstname'],"lastname \%s"=>$row['lastname'],"email \%s"=>$row['email']));
echo json_encode($mynewArray);
this is the screen shot that shows how i tried to do it
I think you could try like this assuming the recordset is generated correctly and available in the var $row
$mynewArray=array();
foreach($result as $row){
$mynewArray[]=$row;
}
echo json_encode($mynewArray);
Or
$mynewArray=array();
foreach( $result as $row ){
$mynewArray[]=array(
'firstname'=>$row['firstname'],
'lastname'=>$row['lastname'],
'email'=>$row['email'],
);
}
echo json_encode($mynewArray);
This might be what you're after:
<?php
$cluster = Cassandra::cluster()
->build();
$keyspace = 'msata';
$session = $cluster->connect($keyspace);
$result = $session->execute(new Cassandra\SimpleStatement
("SELECT * FROM msata.users")
);
// Create the variable array here so it's used correctly in the loop
$mynewArray = array();
foreach( $result as $row ){
// Create an array for each individual user
$user_array = array( 'firstname' => $row['firstname'], 'lastname' => $row['lastname'], 'email' => $row['lastname'] );
// Add the array to the main array
$mynewArray = array_push( $mynewArray, $user_array );
}
echo json_encode( $mynewArray );

Invalid Array from json_decode()

I have a PHP file that grabs a .txt file and decodes the JSON to push the user's e-mail and name entry to my campaign monitor database. The JSON is wonky because new entries are added with a ][ as seen in this example:
[{"email":"drake.scott#test.com","createdate":"2016-03-23 10:44:52","from_email":null,"from_liked_pageid":null,"source":"direct","bonus_entry_url":"\/xxxbyn\/h1lvw5","entry_url":"https:\/\/admin.woobox.com\/manage\/offers\/entries\/20160314-1\/tu%2BcJmnsgyUxE7HM9BCqnRjnza27dGIdr%2BHymHrFmFoprsRgkhZradPrTJ5s18p6ewxYeOOKLpObd%2FWGAS%2BDRw%3D%3D","shareurl":"http:\/\/woobox.com\/qbxbyn\/h1lvw5","picked":"0","actionbutton":"","custom_3_first":"drake","custom_3_last":"scott","custom_4":"4146583264","fullname":"drake scott","id":"vvvbyn"}]
[{"email":"john.roberts#test.com","createdate":"2016-03-23 10:44:52","from_email":null,"from_liked_pageid":null,"source":"direct","bonus_entry_url":"\/xxx\/h1lvw5","entry_url":"https:\/\/admin.woobox.com\/manage\/offers\/entries\/20160314-1\/tu%2BcJmnsgyUxE7HM9BCqnRjnza27dGIdr%2BHymHrFmFoprsRgkhZradPrTJ5s18p6ewxYeOOKLpObd%2FWGAS%2BDRw%3D%3D","shareurl":"http:\/\/woobox.com\/vvvbyn\/h1lvw5","picked":"0","actionbutton":"","custom_3_first":"john","custom_3_last":"adams","custom_4":"4146585018","fullname":"john adams","id":"vvvbyn"}]
The problem I am having right now is uploading the entries to my database. I have managed to strip the ][ and doing a var_dump($content); shows a valid JSON string. However, doing var_dump($user) gives me 0 array(0) { }.
The entries will not upload to my database because there is essentially nothing in my array. Can anyone give me some insight on how to proceed?
<?php
require_once 'csrest_general.php';
require_once 'csrest_subscribers.php';
$auth = array(
'api_key' => 'xxxxxxxxxx');
$wrap = new CS_REST_Subscribers('xxxxxxxxxx', $auth);
$url = 'http://www.mywebsite.com/sweeps/test.txt';
$content = file_get_contents($url);
$content = str_replace('}][{', '},{', $content);
$tmp = explode('][', $content);
foreach ($tmp as $json_part) {
$user = json_decode('['.rtrim(ltrim($json_string, '['), ']').']', true);
$result = $wrap->add(array(
'EmailAddress' => $user->email,
'Name' => $user->fullname,
'Resubscribe' => true
));
}
if($result->was_successful()) {
echo "Subscribed with code ".$result->http_status_code;
}
else {
echo "failed";
var_dump($result->response);
var_dump($user);
}
?>
There are multiple JSON objects concatenated in the file. The easiest way to make the JSON valid is to create an array:
$content = str_replace('][', ',', $content);
$users = json_decode($content, true);
Then you have a multi-dimensional array with multiple users that you will need to decide what you want from it:
print_r($users);
foreach($users as $user) {
echo $user['email'] . "\n";
}

Get data from XML with PHP

below is part of my XML where I try to get data from, basicly I need to insert them to array where "role" is key and "entry" is value.
Here is XML:
<CommunicationDetailList>
<CommunicationDetail>
<Role>Phone1</Role>
<Entry>727831333</Entry>
</CommunicationDetail>
<CommunicationDetail>
<Role>Mobile</Role>
<Entry>727834125</Entry>
</CommunicationDetail>
<CommunicationDetail>
<Role>Fax1</Role>
<Entry>123456789</Entry>
</CommunicationDetail>
<CommunicationDetail>
<Role>EMail1</Role>
<Entry>moj#mail.sk</Entry>
</CommunicationDetail>
</CommunicationDetailList>
This is my PHP code, unfotunately it doesn't work correctly (add just first one not rest of it, so I have access just to Phone1):
//this is somewhere on top of my code
$doc = new DOMDocument();
//Load XML to DOM
$doc->loadXml($xml);
.
.
// here I parse rest of XML, where `<tags>` are unique
.
.
//and here is that important part
$communicationDetails = $doc->getElementsByTagName( "CommunicationDetailList" );
foreach( $communicationDetails as $detail )
{
$keys = $detail->getElementsByTagName( "Role" );
$key = $keys->item(0)->nodeValue;
$values = $detail->getElementsByTagName( "Entry" );
$value = $values->item(0)->nodeValue;
//adding login and password to array
$data[$key] = $value;
}
Can someone help me to access to this XML
Try using SimpleXMLElement like this
<?php
$xml = 'data.xml';
//load xml from file
$doc = simplexml_load_file($xml);
// or load from string
// $doc = simplexml_load_string($xmlString);
foreach($doc->CommunicationDetail as $detail){
//print $detail->Role . ' - ' . $detail->Entry . PHP_EOL;
$data[(string)$detail->Role] = (string)$detail->Entry;
// we cast the xml elements as strings to be used as keys and values in the array
}
print_r($data);
//output is
Array
(
[Phone1] => 727831333
[Mobile] => 727834125
[Fax1] => 123456789
[EMail1] => moj#mail.sk
)
Try this may be it help
foreach( $communicationDetails as $detail )
{
$keys = $detail->getElementsByTagName( "Role" );
$values = $detail->getElementsByTagName( "Entry" );
$length = $keys->length;
for($i = 0; $i <= $length; $i++)
{
$key = $keys->item($i)->nodeValue;
$value = $values->item($i)->nodeValue;
$data[$key] = $value;
}
}
The problem is with
$item(0)
If you were to use a iterated loop like
for ($i=0; $i<count($keys); $i++) { echo $keys[$i]; }
Then it would go through the entire array.

Iterating through an associative array

I am trying to get all twitter followers for a specific user with this API call
https://api.twitter.com/1/users/lookup.json?screen_name=twitterapi,twitter&include_entities=true
And there is a sample output there:
https://dev.twitter.com/docs/api/1/get/users/lookup
I am trying to get the screen name of the user by doing the following:
$json2=file_get_contents('http://api.twitter.com/1/users/lookup.json?user_id='.$post.'') ;
$accounts2 = json_decode($json2);
while( $element = each( $accounts2 ) ) {
echo $element[ 'screen_name' ];
echo '<br />';
}
where $post is all the ids (around 100) concatenated together.
The above would fail with:
Notice: Trying to get property of non-object
Any help please?
Replace this line:
$accounts2 = json_decode($json2);
With this:
$accounts2 = json_decode($json2, true);
It converts it into an associative array. Because user_id is unique, you don't have to loop through the results, but can simply do this:
echo $accounts2[0]['screen_name'] . '<br />';
This worked.
$json2=file_get_contents('http://api.twitter.com/1/users/lookup.json?user_id='.$post.'') ;
$accounts2 = json_decode($json2);
foreach ($accounts2 as $key => $jsons) {
foreach($jsons as $key => $value) {
if($key == 'screen_name'){
echo $value;
}
}
}
Use this.
$json2=file_get_contents('http://api.twitter.com/1/users/lookup.json?user_id='.$post.'') ;
$accounts2 = json_decode($json2,true);
echo $accounts2[0]['screen_name'];

Categories