How can I use str_replace with array for multiple items? - php

I have this code:
libxml_use_internal_errors(TRUE);
$dom = new DOMDocument;
$dom->Load('/home/dom/public_html/cache/feed.xml');
$xmlor = '/home/dom/public_html/cache/feed.xml';
// open file and prepare mods
$fh = fopen($xmlor, 'r+');
$data = fread($fh, filesize($xmlor));
$dmca_claim_jpg = array( 'baduser_.jpg','user78.jpg' );
$dmca_claim_link = array( 'mydomain.com/baduser_','mydomain.com/user78' );
echo "Opening local XML for edit..." . PHP_EOL;
$new_data = str_replace("extdomain.com", "mydomain.com", $data);
$new_data2 = str_replace($dmca_claim_jpg, "DMCA.jpg", $data);
$new_data3 = str_replace($dmca_claim_link, "#", $data);
fclose($fh);
// run mods
$fh = fopen($xmlor, 'r+');
fwrite($fh, $new_data);
fwrite($fh, $new_data2);
fwrite($fh, $new_data3);
echo "Updated feed URL and DMCA claims in local XML..." . PHP_EOL;
fclose($fh);
It does not give any errors when executing but messes up the xml file by removing the first two lines (weird) when fwriting $new_data2 and $new_data3 to xml file.
It works fine writing only $new_data...
I think it has to do with the $dmca_claim_jpg/link arrays.

Parse XML using SimpleXML or DOMDocument it's cleaner and you have a standard OOP way of accessing nodes

Related

Writing to existing JSON array with php

Disclaimer: I am very unfamiliar with PHP. The answers I have seen floating around Stack don't seem applicable to my situation. This could be due to my unfamiliarity.
I need to write to an existing array in a JSON file:
[
[
// data should be written to this array
],
[]
]
My PHP looks like so:
<?php
$ip = $_POST["ip"];
$likes = "../data/likes.json";
$fp = fopen($likes, "a");
fwrite($fp, json_encode($ip) . ", ");
fclose($fp);
?>
When the PHP runs it writes to the end of the file like so (as you'd expect):
[
[
],
[]
]"data",
How do I resolve my PHP to do so?
Open the file:
$filename = '../data/likes.json'
$fp = fopen($filename, 'r');
Then read the existing data structure into a variable:
$data = json_decode(fread($fp, filesize($filename)));
Add the data to the correct array entry:
$data[0][] = $ip;
Close and reopen the file with write privileges, so that we overwrite its contents:
fclose($fp);
$fp = fopen($filename, 'w');
And write the new JSON:
fwrite($fp, json_encode($data));
$ip = $_POST["ip"];
$likes = json_decode(file_get_contents("../data/likes.json"), true);
$likes[] = $ip;
file_put_contents("../data/likes.json", json_encode($likes));
You can not fimply add record to file and get valid json jbject.
So idea of that code:
we read all from file, append array with new data, and rewrite file with new data

What is the proper way to parse yahoo currency http://finance.yahoo.com/connection/currency-converter-cache?date?

As the code i tried and by trial removal to get json content out of the return is below
method i used.
$date= YYYYMMDD;
//example '20140113'
$handle = fopen('http://finance.yahoo.com/connection/currency-converter-cache?date='.$date.'', 'r');
//sample code is http://finance.yahoo.com/connection/currency-converter-cache?date=20140208 paste the url in browser;
// use loop to get all until end of content
while (!feof($handle)) {
$contents .= fread($handle, 8192);
}
fclose($handle);
the code return a given bulk in yahoo and json format
so remove the unknown format which is
"/**/YAHOO.Finance.CurrencyConverter.addConversionRates (" and ends with ");"
by
$contents = str_replace('/**/YAHOO.Finance.CurrencyConverter.addConversionRates(','',$contents);
$contents = str_replace(');','',$contents);
$obj = json_decode($contents,true);
then loop the content by
foreach($obj['list']['resources'] as $key0 => $value0){
}
I prefer to use file_get_contents to get the html and preg_match_all to cleanup the json, i.e.:
<?php
$json = file_get_contents("http://finance.yahoo.com/connection/currency-converter-cache?date=20140113");
preg_match_all('/\((.*)\);/si', $json, $json, PREG_PATTERN_ORDER);
$json = $json[1][0];
$json = json_decode($json,true);
foreach ($json["list"]["resources"] as $resource){
echo $resource["resource"]["fields"]["date"];
echo $resource["resource"]["fields"]["price"];
echo $resource["resource"]["fields"]["symbol"];
echo $resource["resource"]["fields"]["price"];
}
NOTE:
I've tested the code and it works as intended.

Modify text file with php code

I have a JSON file badly formatted (doc1.json):
{"text":"xxx","user":{"id":96525997,"name":"ss"},"id":29005752194568192}
{"text":"yyy","user":{"id":32544632,"name":"cc"},"id":29005753951977472}
{...}{...}
And I have to change it in this:
{"u":[
{"text":"xxx","user":{"id":96525997,"name":"ss"},"id":29005752194568192},
{"text":"yyy","user":{"id":32544632,"name":"cc"},"id":29005753951977472},
{...},{...}
]}
Can I do this in a PHP file?
//Get the contents of file
$fileStr = file_get_contents(filelocation);
//Make proper json
$fileStr = str_replace('}{', '},{', $fileStr);
//Create new json
$fileStr = '{"u":[' . $fileStr . ']}';
//Insert the new string into the file
file_put_contents(filelocation, $fileStr);
I would build the data structure you want from the file:
$file_path = '/path/to/file';
$array_from_file = file($file_path);
// set up object container
$obj = new StdClass;
$obj->u = array();
// iterate through lines from file
// load data into object container
foreach($array_from_file as $json) {
$line_obj = json_decode($json);
if(is_null($line_obj)) {
throw new Exception('We have some bad JSON here.');
} else {
$obj->u[] = $line_obj;
}
}
// encode to JSON
$json = json_encode($obj);
// overwrite existing file
// use 'w' mode to truncate file and open for writing
$fh = fopen($file_path, 'w');
// write JSON to file
$bytes_written = fwrite($fh, $json);
fclose($fh);
This assumes each of the JSON object repsentations in your original file are on a separate line.
I prefer this approach over string manipulation, as you can then have built in checks where you are decoding JSON to see if the input is valid JSON format that can be de-serialized. If the script operates successfully, this guarantees that your output will be able to be de-serialized by the caller to the script.

Instagram API: Get posts from a certain user that also has a certain hashtag

I know of these two endpoints: /users/{user-id}/media/recent and /tags/{tag-name}/media/recent
But I'm trying to get only posts by a certain user that also have a certain hashtag. Is there an easy way of doing this?
Currently I'm using the Instagram PHP API library, doing something like this:
require 'vendor/Instagram-PHP-API/instagram.class.php';
$api = new Instagram('API KEY');
// Get Hashtag Search
$result = $api->getTagMedia('somehashtag', 4); // This brings me back the last 4 posts by any user :/
// Store in a local file for JS consumption
$json = json_encode($result);
$file = TEMPLATEPATH . '/js/instagrams.json';
$fh = fopen($file, 'w');
fwrite($fh, $json);
fclose($fh);
Anyone know of an easy way to do this?
This is what I ended up doing, just getting it down somewhere incase anyone else is trying to do the same thing.
require 'vendor/Instagram-PHP-API/instagram.class.php';
$api = new Instagram('API KEY'); // Client ID
// Get Recent Search
$result = $api->getUserMedia('THE USER ID', 20);
$data = $result->data;
$newresult = new stdClass();
$newdata = array();
foreach($data as $index=>$instagram) {
if (in_array('somehashtag', $instagram->tags)) {
array_push($newdata, $instagram);
}
}
$newresult->data = $newdata;
$json = json_encode($newresult);
$file = TEMPLATEPATH . '/js/instagrams.json';
$fh = fopen($file, 'w');
fwrite($fh, $json);
fclose($fh);
So $newresult is my new object that only has posts from the specified user with the specified hashtag.

PHP Script to convert .CSV files to .XML

Just wondering if anyone can point me in the direction of some tips / a script that will help me create an XML from an original CSV File, using PHP.
Cheers
This is quite easy to do, just look at fgetcsv to read csv files and then DomDocument to write an xml file. This version uses the headers from the file as the keys of the xml document.
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', true);
ini_set('auto_detect_line_endings', true);
$inputFilename = 'input.csv';
$outputFilename = 'output.xml';
// Open csv to read
$inputFile = fopen($inputFilename, 'rt');
// Get the headers of the file
$headers = fgetcsv($inputFile);
// Create a new dom document with pretty formatting
$doc = new DomDocument();
$doc->formatOutput = true;
// Add a root node to the document
$root = $doc->createElement('rows');
$root = $doc->appendChild($root);
// Loop through each row creating a <row> node with the correct data
while (($row = fgetcsv($inputFile)) !== FALSE)
{
$container = $doc->createElement('row');
foreach($headers as $i => $header)
{
$child = $doc->createElement($header);
$child = $container->appendChild($child);
$value = $doc->createTextNode($row[$i]);
$value = $child->appendChild($value);
}
$root->appendChild($container);
}
$strxml = $doc->saveXML();
$handle = fopen($outputFilename, "w");
fwrite($handle, $strxml);
fclose($handle);
The code given above creates an XML document, but does not store it on any physical device. So replace echo $doc->saveXML(); with
$strxml = $doc->saveXML();
$handle = fopen($outputFilename, "w");
fwrite($handle, $strxml);
fclose($handle);
There are a number of sites out there that will do it for you.
If this is going to be a regular process rather than a one-time thing it may be ideal to just parse the CSV and output the XML yourself:
$csv = file("path/to/csv.csv");
foreach($csv as $line)
{
$data = explode(",", $line);
echo "<xmltag>".$data[0]."</xmltag>";
//etc...
}
Look up PHP's file and string functions.
Sorry to bring up an old thread but I tried this script and I'm getting a DOM Exception error
The headers of our CSV Files are display_name office_number mobile_number and the error I'm receiving is DOMDocument->createElement('\xEF\xBB\xBFdisplay_name') #1 {main}

Categories