Can't read XML with simplexml_load_file PHP - php

So i am trying to parse data from an XML url and insert it into a table using php, which can be seen here, (please keep in mind there are more products than displayed on this page, i am not trying to get it for just this Product,the code below shows how i am parsing all products) but i keep getting the following errors:
[EDITED]
class DataGrabber {
//The URL where data will be extracted from, which is an XML file
protected $URL = "http://json.zandparts.com/api/category/GetCategories/44/EUR/";
public function call_api($data) {
if(count($data) == 0) return array();
$jsondata = array();
foreach($data as $entry){
$url = $this->URL . $entry['model'] . "/" . urlencode($entry['family']) . "/" . urlencode($entry['cat']) . "/" . $entry['man'] . "/null";
$json = file_get_contents($url);
$data = json_decode($json, true);
if(!empty($data['Products'])){
foreach ($data['Products'] as $id => $product) {
$jsonentry = array(
'productnumber' => $id,
'partnumber' => $product['strPartNumber'],
'description' => $product['strDescription'],
'manu' => $product['Brand']
);
$jsondata[] = $jsonentry;
}
}
}
return $jsondata;
}
}
[NEW ERRORS]
So i have fixed the error:
PHP Warning: file_get_contents(http://json.zandparts.com/api/category/GetCategories/44/EUR/ET10B/E Series/AC Adapter/Asus/null): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request
in /home/svn/dev.comp/Asus.php on line 82
by using urlencode as shown in my code above
This warning below isnt finding the values for the url:
PHP Warning: file_get_contents(http://json.zandparts.com/api/category/GetCategories/44/EUR///04G265003580/Asus/null): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
as you can see after, 44/EUR there are three forward slashes with no data?? How would i resolve this??

The remote server appears to use the Accept HTTP header to choose the output format. With PHP default options it sends back JSON instead of XML:
<?php
echo file_get_contents('http://json.zandparts.com/api/category/GetCategories/44/EUR/ET10B/E%20Series/AC%20Adapter/Asus/null');
... prints:
{"Categories":[{"Brand":null,"Fami...
To specify an Accept header you need to retrieve the data with some other function, e.g.:
<?php
$context = stream_context_create(
array(
'http' => array(
'header' => "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n",
)
)
);
echo file_get_contents('http://json.zandparts.com/api/category/GetCategories/44/EUR/ET10B/E%20Series/AC%20Adapter/Asus/null', false, $context);
... prints:
<?xml version="1.0" encoding="utf-8"?><ProductCategory ...
Tweak it to your exact needs, I just copied the header from my browser.

Here's a code snippet that shows you how to get the values for strPartNumber, strDescription and Brand for all the products in that JSON data:
<?php
$url = 'http://json.zandparts.com/api/category/GetCategories/44/EUR/ET10B/E%20Series/AC%20Adapter/Asus/null';
$json = file_get_contents($url);
// Decode the JSON data as a PHP array
$data = json_decode($json, true);
if (!empty($data['Products'])) {
foreach ($data['Products'] as $id => $product) {
echo "Product #{$id}\n";
echo "Part number: {$product['strPartNumber']}\n";
echo "Description: {$product['strDescription']}\n";
echo "Brand: {$product['Brand']}\n\n";
}
}
Output:
Product #0
Part number: 04G265003580
Description: POWER ADAPTER 65W19V 3PIN
Brand: Asus
Product #1
Part number: 14G110008340
Description: POWER CORD 3P L:80CM,TW(B)
Brand: Asus

Related

PHP and JSON for Reddit

want to grab from a specific Reddit user some data.
There's a dynamic JSON file on the Reddit servers which can be accessed remotely.
The JSON file path is: http://www.reddit.com/user/tiagoperes/about.json
(where you can replace “tiagoperes” in the URL with whatever user you were trying to look up) - thank you Tom Chapin
Problem: I get the error message
http error 500: reddiant.com/reddit.php
Error Log:
PHP Warning:
file_get_contents(https://www.reddit.com/user/tiagoperes/about.json):
failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden on
line 5
PHP Fatal error: Uncaught exception 'InvalidArgumentException'
with message 'Passed variable is not an array or object, using empty
array instead' on line 8
Code:
<?php
$url = "https://www.reddit.com/user/tiagoperes/about.json";
$json = file_get_contents($url);
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($json, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:\n";
} else {
echo "$key => $val\n";
}
}
(inspired in this: http://codepad.org/Gtk8DqJE)
Solution: Ask for debug.
What's the problem right here?
Can not find a way to make it work and should be quite straightforward.
Thank you!
Was getting some troubles in the first procedure, so decided to change the approach.
Got it to work like that:
<?php
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"User-Agent: reddiant api script\r\n"
));
$context = stream_context_create($opts);
$url = "http://www.reddit.com/user/tiagoperes/about.json";
$json = file_get_contents($url, false, $context);
$result = json_decode($json, true);
// Result:
var_dump($result);
//echo data
echo $result['data']['name'];

Simple html dom parser return error 500

I am using simple_html_dom.php library from this example
http://nimishprabhu.com/top-10-best-usage-examples-php-simple-html-dom-parser.html
But i got error 500 inside class, when I type url in browser it works ok?
I have some vaules in array like this
$result= Array (
[Avenya Group AG] =>
Array (
[link] => CHE-218.938.800
[href] => http://zh.powernet.ch/webservices/inet/HRG/HRG.asmx/getHRGHTML?chnr=0203038402&amt=020&toBeModified=0&validOnly=0&lang=1&sort=0 ) )
When I try something like this
foreach($result as $key => $value) {
$xmlFind = file_get_html($value['href']);
foreach($xmlFind->find('a') as $a) {
echo '<p>'.$a->href.'</p>';
}
}
I got error
A PHP Error was encountered
Severity: Warning
Message: file_get_contents(http://zh.powernet.ch/webservices/inet/HRG/HRG.asmx/getHRGHTML?chnr=0203038402&amt=020&toBeModified=0&validOnly=0&lang=1&sort=0): failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error
Filename: libraries/Simple_html_dom.php
Line Number: 76
But when I try manually like this
$xmlFind = file_get_html('http://zh.powernet.ch/webservices/inet/HRG/HRG.asmx/getHRGHTML?chnr=0203038402&amt=020&toBeModified=0&validOnly=0&lang=1&sort=0');
Result is there, also if i type that url i browser all is ok, only problem i have is when i try to loop an array ??
check http://php.net/manual/en/function.file-get-contents.php Notes section.
Please check your server settings for "fopen wrappers"
I tried the following
<?php
include('simple_html_dom.php');
$result= Array (
'Avenya Group AG' =>
Array (
'link' => 'CHE-218.938.800',
'href' => 'http://zh.powernet.ch/webservices/inet/HRG/HRG.asmx/getHRGHTML?chnr=0203038402&amt=020&toBeModified=0&validOnly=0&lang=1&sort=0' ) );
foreach($result as $key => $value) {
$xmlFind = file_get_html($value['href']);
foreach($xmlFind->find('a') as $a) {
echo '<p>'.$a->href.'</p>';
}
}
And got this
#
http://www.shab.ch/shabforms/servlet/Search?EID=7&DOCID=6890948
http://www.shab.ch/shabforms/servlet/Search?EID=7&DOCID=981331
http://zh.powernet.ch/webservices/inet/hrg/hrg.asmx/getExcerpt?Chnr=CH-020.3.038.402-5&Amt=20&Lang=1
mailto:info#powernet.ch
Proxy might be a problem. Use appropriate proxy.
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n",
'proxy' => 'tcp://221.176.14.72:80',
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('http://ifconfig.me/ip', false, $context);
var_dump($file);
Try this,
<?php
$result= Array (
'Avenya Group AG' =>
Array (
'link' => 'CHE-218.938.800',
'href' => 'http://zh.powernet.ch/webservices/inet/HRG/HRG.asmx/getHRGHTML?chnr=0203038402&amt=020&toBeModified=0&validOnly=0&lang=1&sort=0'
)
);
foreach($result as $arr_item){
if(is_array($arr_item)) {
if(isset($arr_item['href'])) {
echo file_get_contents($arr_item['href']);
}
}
}
?>
After executing above code, I got this response as shown into attached image.
If you still get an warning error, you can use curl to send get request.
so instead of echo file_get_contents($arr_item['href']); above
replace it with the following code.
$ch = curl_init($arr_item['href']);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$result = curl_exec($ch);
echo $result;
curl_close($ch);
This message is returned by the remote server. It shows that the server might be unavailable at this time.
I think this might be caused by a too important amount of resources needed to execute the different requests you made within your loop. It can also be linked to some Denial of Service protection.
After reaching the maximum number of authorized connection, it returns "HTTP 500 Server Too Busy".
See: https://www.iis.net/configreference/system.webserver/asp/limits
The requestQueueMax attribute specifies the maximum number of concurrent ASP requests that are permitted into the queue. Any client browser that attempts to request ASP files when the queue is full is sent an HTTP 500 Server Too Busy error.
You can try to delay each of your call to the url with a sleep() if you're not time limited.
The best thing to do is contact the owner/sys admin of the remote web service in order to let him know about the problem so that he could investigate.
Depending of what you are doing in your script you can also ignore the error message and continue with the next call:
foreach($result as $key => $value) {
// added # to ignore the error
$xmlFind = #file_get_html($value['href']);
// continue to the next result
if (!$xmlFind) continue;
foreach($xmlFind->find('a') as $a) {
echo '<p>'.$a->href.'</p>';
}
}

Issue displaying json feed items using PHP

I am very new to json in combination with php and wonder why the following code is not working. My mission is displaying the title items one by one.
<?php
$json_string = file_get_contents("https://www.fiverr.com/gigs/gigs_as_json?host=search&type=single_query&query_string=pet&search_filter=rating&category_id=3&sub_category_id=49&limit=48");
$parsed_json = json_decode($json_string, true);
$parsed_json = $parsed_json['gigs'];
foreach($parsed_json as $key => $value)
{
echo $value['title'] . '<br>';
}
?>
The next issue will by, how would I be able to save the image item called cloud_img_med to my server into /grabbed
Your help would be greatly appreciated.
To answer your question about why this code isn't working:
I tried to set it up myself, and found out that the output fetched by file_get_contents is compressed. You can see that by reading the output in a simple var_dump:
var_dump($json_string);
To fix this, you'll need to use a custom context with no compression:
$context = stream_context_create(
array(
'http' => array(
'method' => "GET",
'header' => "Accept-Encoding: gzip;q=0, compress;q=0\r\n",
)
));
Then pass it as the third parameter:
$json_string = file_get_contents("https://www.fiverr.com/gigs/gigs_as_json?host=search&type=single_query&query_string=pet&search_filter=rating&category_id=3&sub_category_id=49&limit=48", false, $context);
I should do this JSON string readable
The code seems to work fine - I tried it on my local machine.
Running this
<?php
$str = <<<EOT
// JSON here...
EOT;
$parsed_json = json_decode($str, true);
$parsed_json = $parsed_json['gigs'];
foreach($parsed_json as $key => $value)
{
echo $value['title'] . '<br>';
}
?>
Gives me this output
replace the MGM lion with your pet or whoever<br>design creative Animal And Pet Company logo<br>`
Which is sort of what you want? If you're having trouble, maybe file_get_contents isn't allowed on your server and you can't get the JSON. Try hardcoding it into the $str variable like I did, and see if you get what you want.
With regards to saving the image, you can check this answer here: https://stackoverflow.com/a/724449/4396258
I think the problem might be the data you're getting from Fiverr's JSON API. At least in my test, I found it was using gzip encoding to compress the data you're requesting. So you have to uncompress it.
$json_string = file_get_contents("https://www.fiverr.com/gigs/gigs_as_json?host=search&type=single_query&query_string=pet&search_filter=rating&category_id=3&sub_category_id=49&limit=48");
$content = json_decode(gzinflate( substr($json_string,10,-8) ));
$gigs = $content->gigs;
foreach($gigs as $key => $value)
{
echo $value->title . '<br>';
}

PHP post request returns 400 error

I have the following class, it's using a web service to send a request and get a JSON response back.
When i try the same thing with Chrome's Postman extension, I get a nice little response back.
class RequestController {
function __construct() {
global $config;
$this->config = $config;
}
function send_request() {
$url = $this->config['GATEWAY']['url'] . 'getbyquery';
$json_data = '{"query":{"AllFields":true,"ConditionSetOperator":0,"ConditionSets":[],"Distinct":false,"Fields":["jay_alb","jay_levelms"],"Links":[],"Orders":[],"RecordType":"jay_lifeinsurance","Top":0}}';
$data = array($json_data);
$options = array(
'http' => array(
'header' => "Content-type: application/json\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
print "<pre>";
print_r($options);
print "</pre>";
$result = file_get_contents($url, false, $context);
$data = json_decode($result);
var_dump($data);
}
}
However when I'm using my class I get an error.
Warning: file_get_contents(http://crm-gateway.premier.com.au/GatewayService.svc/getbyquery) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 411 Length Required in C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs\crm\includes\classes\RequestController.php on line 32
Can you please point out what I'm doing wrong?
Thanks,

Requesting information from one php file to another using only php

I am pretty new to php so I'm having trouble with POSTing.
I am trying to transfer information between 2 php files where send_var.php sends a command by POST and get_var.php executes some data manipulation and returns the response.
The send_var.php is as follows:
<?php
$url = "./get_var.php";
$fields = array('response' => "323243");
$data = http_build_query($fields);
// echo $data."<br />";
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Content-type: text/html\r\n",
'content' => $data
),
));
$out = file_get_contents($url, false, $context);
echo "Info from get_var : " . $out;
?>
And the get_var.php is :
<?php
$arg1 = isset($_POST['response']) ? $_POST['response'] : null;
if($arg1 == '')
{
echo "No Command! ";
}
if($arg1 != "")
{
echo $_POST['response'];
}
else
{
$_POST['response'] = "123456";
echo $_POST['response'] . " end of get_var";
}
?>
This code was extracted from other examples on stack overflow. The only output I get is "Info from get_var :"
Obviously I'm missing some pretty fundamental knowledge. If someone can help it would be much appreciated. I'm executing this under XAMPP.
In order to run a PHP script, you have to access it through the webserver. So the URL needs to be an http: URL, not just a filename:
$url = "http://localhost/path/to/get_var.php";
If you just use a filename, file_get_contents() will just return the PHP source code, it won't run it.
Also, your Content-type header is wrong, it should be application/x-www-form-urlencoded, not text/html (that's the content type of the response, your context specifies the type of the POST data).

Categories