How to access array list in Json by php? - php

I am currently working with Accessing json using php in wordpress. I have successfully decoded the json but when i try to access the values it doesn't fetch . I am trying to access the Cluster_ID and Image
values.
Here's my api link http://ec2-13-127-149-66.ap-south-1.compute.amazonaws.com:5000/api/news
I have tried the following code:
<?php
/**
*Plugin Name: plugin two
**/
function myjson8(){
$request = wp_remote_get( 'http://ec2-13-127-149-66.ap-south-1.compute.amazonaws.com:5000/api/news' );
if( is_wp_error( $request ) ) {
return false; // Bail early
}
$body = wp_remote_retrieve_body( $request );
$data = json_decode( $body );
if( ! empty( $data) ) {
foreach( $data as $product ) {
echo $product->Cluster_ID;
foreach($data->data as $news){
echo $news->Image;
}
}
}
}

Taking the data from the news feed that you supplied then placing it in a JSON viewer you get:
On opening level 0 we get
This is not what you want so we need to look at level 1 and its structure
So your code would be:
for($x=0; $x<count($data[1]); $x++ ) {
$clusterId = $data[1][$x]['Cluster_ID'];
for( $p=0; $p<count( $data[1][$x]['data'] ); $p++ ) {
$pic = $data[1][$x]['data'][$p];
}
}

Related

How to optimize tree like fetching from WP rest-api (with CPT & ACF)

I'm trying to fetch tree-like data from WordPress rest API and save it as an array. I have a custom post type and every "post" in that CPT has custom fields "mom" and "dad". Those fields are relational ACF fields that link to another post (that belong to the same CPT).
So the child post "only knows" its parents and then if we want to fetch the grandparent, we have to go and check the parents of the parents.
Structure:
person
-dad
--dad´s dad
--dad´s mom
-mom
--mom´s dad
--mom´s mom
I would like to create a simple array of the family tree, but it's taking ages to fetch it and I think it could be optimized but not sure how.
The current structure for creating the family tree array:
function fetchFamilyTree($horse_id) {
$response = wp_remote_get( 'https://..../wp-json/wp/v2/horse/' . $horse_id );
// Exit if error.
if ( is_wp_error( $response ) ) {
return;
}
// Get the body.
$horse_info = json_decode( wp_remote_retrieve_body( $response ) );
// Exit if nothing is returned.
if ( empty( $horse_info ) ) {
return;
}
if ( !empty( $horse_info ) ) {
$tree = array();
$suku['i'] = $horse_info->acf->dad;
$suku['ii'] = haeHevosenIsa($suku['i']);
$suku['iii'] = haeHevosenIsa($suku['ii']);
$suku['iie'] = haeHevosenEma($suku['ii']);
$suku['ie'] = haeHevosenEma($suku['i']);
$suku['iei'] = haeHevosenIsa($suku['ie']);
$suku['iee'] = haeHevosenEma($suku['ie']);
$suku['e'] = $horse_info->acf->mom;
$suku['ei'] = haeHevosenIsa($suku['e']);
$suku['eii'] = haeHevosenIsa($suku['ei']);
$suku['eie'] = haeHevosenEma($suku['ei']);
$suku['ee'] = haeHevosenEma($suku['e']);
$suku['eei'] = haeHevosenIsa($suku['ee']);
$suku['eee'] = haeHevosenEma($suku['ee']);
return $tree;
}
}
"haeHevosenEma" and "haeHevosenIsa" are helper functions like this to fetch the dad's or mom's id:
function haeHevosenEma($horse_id) {
$response = wp_remote_get( 'https://..../wp-json/wp/v2/horse/' . $horse_id );
// Exit if error.
if ( is_wp_error( $response ) ) {
return;
}
// Get the body.
$horse_info = json_decode( wp_remote_retrieve_body( $response ) );
// Exit if nothing is returned.
if ( empty( $horse_info ) ) {
return;
}
if ( !empty( $horse_info ) ) {
return $horse_info->acf->ema;
}
}
And no, I cannot save the data as an array to the person's profile. Every single person should be "their own post" and this relational data structure is key for other use cases.
Edit// Here's an example of the page load (over 52s) - something is wrong clearly. Without this family tree fetching the load time is under 2s.
image of the page load

Wordpress - Record in the db, data obtained from json

I wrote this plugin that perfectly receives and shows data from an external API.
Code:
function get_posts_via_rest() {
$request = wp_remote_get( 'http://xxx' );
if( is_wp_error( $request ) ) {
return false; // Bail early
}
$body = wp_remote_retrieve_body( $request );
$risposta_json = json_decode( $body );
//print_r($data);
if( ! empty( $risposta_json ) ) {
foreach($risposta_json->data->offerte->data as $offerta ){ // now iterate through that array
if($offerta->struttura->id == aggancio_id_campo_uno()){ // check all conditions
echo '<ul>';
echo '<li>'.$offerta->struttura->nome .'</li>';
echo '<li>'.$offerta->struttura->url_completo .'</li>';
echo '<li>'.$offerta->titolo .'</li>';
echo '</ul>';
}
}
}
}
// Register as a shortcode to be used on the site.
add_shortcode( 'sc_get_posts_via_rest', 'get_posts_via_rest' );
Now I have created a type of custom post called bids, as this code shows all the bids for a given company id, which is set with an input field that I didn't put here because it was superfluous, my question is how do I now have the data from json to register them inside the db?
May this help you:
global $wpdb;
$table = $wpdb->prefix.'you_table_name';
$data = array('column1' => 'data one', 'column2' => 123);
$format = array('%s','%d');
$wpdb->insert($table,$data,$format);
$my_id = $wpdb->insert_id;

Searching XML using XPath for multiple attributes in php

I found same topics but I didn't solve my problem :(
I want to search in XML with product code
this is my code;
$xml = simplexml_load_file('http://xml.aksel.com.tr/Xml.aspx?SK=d021da08&CK=50288');
$product_code = $_GET['s'];
$products = $xml->xpath("//STOK_KODU[contains(text(), '".$product_code."')]/STOK_ADI/GRUPKODU");
if I remove "/STOKADI/GRUPKODU", its working. But Product title, product image, product category didn't show. Where is the problem?
And my second problem, when I want to show all products; I see some products at least 4-5 times.
(Note: I work in WordPress)
I don't use simple_xml but the approach below, using DOMDocument and DOMXPath should be easy enough to port to simple_xml if desired. Initially I thought you were looking for child nodes of STOK_KODU but the structure of the XML suggests otherwise. The XPath query will find the node with the relevant $product_code from which you can easily find the parent and thus any/all of it's children.
$file='http://xml.aksel.com.tr/Xml.aspx?SK=d021da08&CK=50288';
#$file='c:/temp/Xml.xml'; /* saved locally to test */
$output=array();
$product_code=13775;
$query='//XMLWEBDATA/STOK_KODU[ contains( text(), "'.$product_code.'" ) ]';
$dom=new DOMDocument;
$dom->load( $file );
$xp=new DOMXPath( $dom );
$col=$xp->query( $query );
if( $col && $col->length > 0 ){
foreach( $col as $node ){
/* get the parent */
$parent=$node->parentNode;
$data=array();
for( $i=0; $i < $parent->childNodes->length; $i++ ){
$tag=$parent->childNodes->item( $i )->tagName;
$value=$parent->childNodes->item( $i )->nodeValue;
if( !empty( $tag ) && !empty( $value ) ) $data[ $tag ]=$value;
}
$output[]=$data;
}
/* remove duplicates if there are any */
$output=array_unique( $output );
}
$xp = $dom = null;
/* process the results accordingly */
if( !empty( $output ) ){
foreach( $output as $obj ){
printf('<pre>%s</pre>', urldecode( http_build_query( $obj, null, PHP_EOL ) ) );
}
}
The output of which will be
STOK_KODU=13775
STOK_ADI=CHIP EPSON C3800 Black (S051127)
LISTEFIYAT=2,73
STOKBAKIYE1=16
GRUPKODU=DOLUM ÜRÜNLERİ GRUBU
KOD1=TONER DOLUM ÜRÜNLERİ
KOD2=ÇİPLER
PARABIRIMI=$
KULL5N=9500
RESIMURL=http://xml.aksel.com.tr/Photo.aspx?ID=22705&STOK=13775
To access each field as a variable ( which is what I understand your comment to be )
foreach( $col as $node ){
/* get the parent */
$parent=$node->parentNode;
$data=array();
for( $i=0; $i < $parent->childNodes->length; $i++ ){
try{
/* test node type to avoid errors */
if( $parent->childNodes->item( $i )->nodeType==XML_ELEMENT_NODE ){
$tag=$parent->childNodes->item( $i )->tagName;
$value=$parent->childNodes->item( $i )->nodeValue;
if( !empty( $tag ) && !empty( $value ) ) $data[ $tag ]=$value;
}
}catch( Exception $e ){
echo $e->getMessage();
continue;
}
}
$output[]=$data;
}
and to access as variables, use extract
if( !empty( $output ) ){
foreach( $output as $obj ){
extract( $obj );
printf("<pre>%s\n%s\n%s</pre>", $STOK_KODU, $STOK_ADI, $GRUPKODU );
}
}
If you look at the structure of the XML, the GRUPKODU and STOKADI are elements at the same level. So trying to access these in you XPath at the same time isn't going to work. If instead you look for the XMLWEBDATA element your after, you can then access these elements inside this element. This XPath looks for an XMLWEBDATA with a STOK_KODU with content that contains the product code your after, then using foreach to print out each match, it outputs the two values your after...
$products = $xml->xpath("//XMLWEBDATA[STOK_KODU[contains(text(), '".$product_code."')]]");
foreach ( $products as $product ) {
echo (string)$product->STOK_ADI.PHP_EOL;
echo (string)$product->GRUPKODU.PHP_EOL;
}
(I only cast the return values to strings as this is needed if assigning to other values, echo will automatically cast it anyway and it can cause confusing results when used in assignments)
If I set
$product_code = 14037;
This outputs
EPSON T2711XL (27XL) > WF3620,3640,7110,7610,7620 Black
TÜKETİM ÜRÜNLERİ GRUBU
Note: You may want to use....
$products = $xml->xpath("//XMLWEBDATA[STOK_KODU='".$product_code."']");
to ensure that you only find a code that fully matches in case there are cases where it will match parts of other codes.

Show balance in PHP using API?

I'm trying to show SMS balance using an API in a PHP page.
What am I missing to simplify this? (The API is working fine directly):
public function show_sms_credits() {
if ( false === ( $my_query = get_transient( 'available_sms_credits' ) ) ) {
$api_key = get_option( 'wc_api_key', true );
$api_token = get_option( 'wc_api_token', true );
if( empty ( $api_key ) || empty( $api_token ) ){
return;
}
$url = 'http://mywebsite.com/api/';
$response = wp_remote_get("{$this->url}GetBalance?User={$this->api_key}&Password={$this->api_token}");
if( ! is_wp_error( $response ) && 200 == wp_remote_retrieve_response_code( $response ) ) {
$body = json_decode( wp_remote_retrieve_body( $response ) );
set_transient( 'available_sms_credits', $body->sms_credits, 12 * HOUR_IN_SECONDS );
}
}
$sms_credits = get_transient( 'available_sms_credits' );
}
}
<p> SMS Balance: <?php echo 'available_sms_credits': ?> </p>
Because you use this syntax
$url = 'http://mywebsite.com/api/';
You should simply use
$response = wp_remote_get("{$url}GetBalance?User={$api_key}&Password={$api_token}");
Because you've only assigned local variables, not assignments to the current object itself. If you needed to add the URL as a property against your object you'd have use $this like...
$this->url = 'http://mywebsite.com/api/';
Also your're not doing anything with $sms_credits

Pinterest Wordpress Plugin Display Image

I am currently trying to create a plugin using Pinterest for Wordpress. I have ran into a slight problem, I've been trying to return an image with a link but only been able to only return a link.
<?php
function displayPinterest()
{
$request = wp_remote_get( 'https://api.pinterest.com/v1/boards/mercurizen/shoeswatches/pins/?access_token=AXgIMQmjCFDXyJsHni0wYUdZxshcFETISS1nfSRDAz1G7WBDJgAAAAA&fields=image,note,link&limit=5' );
$pins = json_decode( $request['body'], true );
if( !empty( $pins['data'] ) ) {
echo '<ul>';
foreach( $pins['data'] as $pin ) {
echo '<li>' . $pin['note']. '</li>';
}
echo '</ul>';
}
}
?>
Anyone experienced with Wordpress Plugins and Pinterest can help me with this problem ?
Try to change your code as below. You will get text in $pin['note'] and image url in $img['url'].
function displayPinterest()
{
$request = wp_remote_get( 'https://api.pinterest.com/v1/boards/mercurizen/shoeswatches/pins/?access_token=AXgIMQmjCFDXyJsHni0wYUdZxshcFETISS1nfSRDAz1G7WBDJgAAAAA&fields=image,note,link&limit=5' );
$pins = json_decode( $request, true );
if( !empty( $pins['data'] ) ) {
echo '<ul>';
foreach( $pins['data'] as $pin ) {
$img = $pin['image']['original'];
echo '<li>' . $pin['note']. '</li>';
}
echo '</ul>';
}
}

Categories